0

I'm brand new to Java and we're learning about inheritance and subclasses. In the text and online it is said that subclasses do not inherit constructors from their respective superclasses; however in a quiz question we were asked the output of the following code;

class Food {
    Food() { printFlavor(); }
    void printFlavor() { System.out.println("bland"); }
}
class Pepper extends Food {
    void printFlavor() { System.out.println("spicy"); }
}
public class Lunch {
    public static void main(String[] args) {
        Food lunch = new Pepper();
    }
}

I assumed that since constructors are not inherited that the output should be nothing; because the compiler would use the default constructor for Pepper; however this was incorrect. Am I missing something glaringly obvious? Running it myself I can see that it uses the constructor for Food, since it calls the printFlavor subroutine, but I can't understand why if subclasses don't inherit constructors.

Rob
  • 14,746
  • 28
  • 47
  • 65
  • This might help: https://stackoverflow.com/a/10508202/6512857 – Will Oct 07 '20 at 19:54
  • @Will This did help, actually, thank you! I had been getting the feeling that it was some sort of implicit call but hadn't seen anything that would point that out so wasn't sure. Thanks a lot! – Cameron Truitt Oct 09 '20 at 00:26

0 Answers0