A basic Java question

Discussion in 'App Development' started by blueraincap, Feb 20, 2017.

  1. 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: }
     
  2. southall

    southall

    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?
     
  3. It says
    -----------------------------------------
    the output is MammalPlatypus, since the super constructor is executed before the child constructor.
     
  4. southall

    southall

    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.
     
    Last edited: Feb 21, 2017
  5. ET180

    ET180

    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.
     
  6. ET180

    ET180

    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.
     
  7. southall

    southall

    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.
     
    Zzzz1 likes this.
  8. jj90

    jj90

    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.
     
  9. Thanks. I run in DrJava and think the book answer is wrong..