0
Why does this print âabâ and not âbâ only?
public class Program { public static void main (String[] args) { B b= new B(); } class A{ public A() { System.out.print("a"); } { class B extends A{ public B() { System.out.print ("b"); } }
5 Answers
+ 4
HoaiNam
A is your superclass, B is your subclass.
When calling a subclass (an extended version of the superclass) all constructors are called top-to-bottom.
B is an extension of A so A constructor is called then B constructor.
If your trying to only call A constructor that wonât work and suggests your object modelling is wrong.
JVM will always create an object of the superclass, so that you can access/use its methods in th subclass - thats why the superclass constructor is always called.
+ 3
HoaiNam because you extends the class A this role known as inheritance and if you don't know then please learn about this what is inheritance?
+ 2
Because you extends class A
+ 2
Your parents class needs to be constructed first thats why the constructor in A was called once thats all set up it moves to the subclass and constructs them.
you can get it to print just "a" but not just "b"
DavX has it figured
0
But I only call the constructor of B? So why dies it call the constructor of A too