Why another constructor is not running during class B initialization? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why another constructor is not running during class B initialization?

class A { public A() { System.out.println("New A"); } public A (String name){ System.out.println("New A 1"); } } class B extends A{ public B() { System.out.println("New B"); } } class Program { public static void main(String[ ] args) { B obj = new B(); } } //output New A New B but not also New A 1

1st May 2016, 8:09 AM
Rajesh
Rajesh - avatar
5 Answers
+ 4
Because only the default constructor is called. You have not initialized an object with the constructor that takes a String parameter.
18th May 2016, 3:40 PM
James Flanders
+ 1
you have to pass a string as an argument/parameter while you create an object/instance of the class..
30th Jun 2016, 5:55 PM
Ravi Chandra Asthana
Ravi Chandra Asthana - avatar
0
you have to call the A constructor with string in order to have New A 1 example A obj = new A ("dfgg") or B obj = new B ("sdfdd")
12th Jun 2016, 7:38 PM
Albert Assaad
Albert Assaad - avatar
0
for that u need to pass string as a parameter there. like B obj = new B("hello");
24th Jun 2016, 7:26 AM
Saud Ahmad
Saud Ahmad - avatar
0
In class B In the no argument constructor the compiler is going to place public B() { super(); sop("New B"); } it means it's a call to no argument constructor for the parent class. if the parent class doesn't have no argument constructor then it call's default constructor of parent class.
24th Aug 2016, 2:27 AM
Sarath chalapaka
Sarath chalapaka - avatar