Inheritance | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Inheritance

Please i don't understand why the output of this code gives /* New A New B */ class A { public A() { System.out.println("New A"); } } class B extends A { public B() { System.out.println("New B"); } } class Program { public static void main(String[ ] args) { B obj = new B(); } } That's, I thought the would be /* New B */.

5th Jun 2017, 9:24 PM
Daniel Graham
3 Answers
+ 4
The super class constructor is invoked upon creation of the object. Think of it as the compiler adding the super() keyword above everything in the class B constructor if it is not manually written.
5th Jun 2017, 9:32 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
B is a child of A, therefore to create B. A MUST BE CREATED FIRST! What happens when A gets created? You print New A Then B gets created. What happens when B gets created? You print New B The result is New A New B. Remember they have a parent child relationship. Children can't exist if parents don't make them.
5th Jun 2017, 9:53 PM
caleb
caleb - avatar
0
OK thanks to you all. I got the understanding.
6th Jun 2017, 8:11 PM
Daniel Graham