I looked at a book question and the output for the below code is "MammalPlatypus". Can you please explain why? I see that if a Platypus object is created (no arg), the Platypus constructor calls the Mammal constructor then back to itself, resulting in MammalPlatypus. But I see it is creating a Mammal object below, so why not only the Mammal constructor is invoked? Can't you create a superclass instance from a subclass? why would that end up invoking the subclass constructor? What is the output of the following code? 1: class Mammal { 2: public Mammal(int age) { 3: System.out.print("Mammal"); 4: } 5: } 6: public class Platypus extends Mammal { 7: public Platypus() { 8: super(8); 9: System.out.print("Platypus"); 10: } 11: public static void main(String[] args) { 12: new Mammal(5); 14: } 14: }
The answer is "Mammal" not "MammalPlatypus". new Platypus(); would print "MammalPlatypus" So your understanding is correct, but the answer is wrong. Are you sure you looking at the right answer?
It says ----------------------------------------- the output is MammalPlatypus, since the super constructor is executed before the child constructor.
new Platypus(); would print: MammalPlatypus but 11: public static void main(String[] args) { 12: new Mammal(5); 14: } Will print only: Mammal So its a mistake in the book, the book answer is wrong. run the code yourself and see.
What might be helpful with these kinds of questions is simply running the code in an IDE debugger like Eclipse. You can step through the code line by line, read variables, and see what happens.
Southall is correct, you can delete the Platypus class entirely. It's not even used by the main call. Funny that the age parameter is also not used.
Or the code is wrong, it should say 11: public static void main(String[] args) { 12: new Platypus(); 14: } Then the given answer and explanation would be correct.
Agree with the rest: 1)There is no call to Platypus in main(). Platypus doesn't do anything. 2)This isn't 1982. Run the code in even the most basic of IDEs.