-1

I want to know why the following code:

public class Vertebrate {

   public Vertebrate() {
      System.out.print("Vertebrate ");
   }

   public static void main(String[] args) {
      Mammal rabbit = new Mammal();
      System.out.println("Rabbit");
   }
}

class Mammal extends Vertebrate {
   public Mammal() {
      System.out.print("Mammal ");
   }
}

produces the output: Vertebrate Mammal Rabbit.

I was asked to explain in detail, but I don't understand why the output is like it is. Please someone help me out.

Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135
Leonardo
  • 19
  • 1
  • 6
  • 1
    What do you think? Why is the output as it is? Did you try to follow the execution path of the program? – Andreas Fester May 19 '16 at 09:25
  • @AndreasFester I think it is because Mammal extends Vertebrate but I don't know ow to write a detailed explanation on that. – Leonardo May 19 '16 at 09:27

4 Answers4

4

You instantiate Mammal which implicitly calls super() before anything which invokes the default constructor of Vertebrate. This prints Vertebrate first. Then it continues with the constructor of Mammal which prints Mammal and then finally Rabbit.

For a more complex/advanced case of inheritance/constructors/overriding I have written a Q+A a while back.

Community
  • 1
  • 1
Idos
  • 15,053
  • 14
  • 60
  • 75
0

There is an implicit call to default constructor of super-class :

class Mammal extends Vertebrate {
   public Mammal() {
      super();
      System.out.print("Mammal ");
   }
}
Pinguet62
  • 36
  • 1
  • 4
0

As you know the main method executes first. So these two lines are executed sequentially.

Mammal rabbit = new Mammal();
System.out.println("Rabbit");

So you can see why rabbit gets printed last. Now for the first line ,

When you write Mammal rabbit = new Mammal(); you are creating an instance of the Mammal Class right. Now new Mammal() calls the mammal class's constructor. For any Java class the first line of the constructor is this.super() It does not matter whether you write it or not. Java does it for you.

So inside Mammal constructor the super class ie. Vertebrate gets instantiated first. This causes the Vertebrate to printed before mammal.

Som Bhattacharyya
  • 3,972
  • 35
  • 54
0

As the subclass constructor implicitly calls the super()

/* calling super() must be the first statement in the sub class constructor in case of explicit call*/

for more info : http://docs.oracle.com/javase/tutorial/java/IandI/super.html

Pankaj Verma
  • 191
  • 10