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"); } }

31st Jan 2023, 1:51 PM
HoaiNam
HoaiNam - avatar
5 Respuestas
+ 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.
31st Jan 2023, 2:12 PM
DavX
DavX - avatar
+ 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?
31st Jan 2023, 2:03 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
+ 2
Because you extends class A
31st Jan 2023, 1:56 PM
Sakshi [Offline 🙃]
Sakshi [Offline 🙃] - avatar
+ 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
1st Feb 2023, 12:45 AM
D_Stark
D_Stark - avatar
0
But I only call the constructor of B? So why dies it call the constructor of A too
31st Jan 2023, 2:01 PM
HoaiNam
HoaiNam - avatar