+ 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 */.
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.
+ 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.
0
OK thanks to you all. I got the understanding.