class A
{
public A() {} // A1
public A(String s) { this(); System.out.println("A :"+s); } // A2
}
class B extends A
{
public int B(String s) { System.out.println("B :"+s); return 0; } // B1
}
class C extends B
{
private C(){ super(); } // C1
public C(String s){ this(); System.out.println("C :"+s); } // C2
public C(int i){} // C3
}
So while constructing an object of class C, it would try to invoke the default constructor of class B, which is absent, so it can't be called, wherefore there will never be a call to the constructor of class A.
pushpull wrote:So while constructing an object of class C, it would try to invoke the default constructor of class B, which is absent, so it can't be called, wherefore there will never be a call to the constructor of class A.
Why do you think that while constructing an object of class C, it would try to invoke the default constructor of B?
If you like our products and services, please help us by posting your review here.
That doesn't answer why you think it would try to invoke the default constructor of B. It only answers that creating an instance of C would cause a constructor of B to be invoked.
If you like our products and services, please help us by posting your review here.
Mayby I'll quote the Katty Perry SCJP book. Page 143:
Key Rule: The first line in a constructor must be a call to super() or a call to
this().
No exceptions. If you have neither of those calls in your constructor, the compiler
will insert the no-arg call to super(). In other words, if constructor A() has a call
to this(), the compiler knows that constructor A() will not be the one to invoke
super().
The preceding rule means a constructor can never have both a call to super()
and a call to this(). Because each of those calls must be the first statement in a
constructor, you can't legally use both in the same constructor. That also means the
compiler will not put a call to super() in any constructor that has a call to this().
Moreover, here we have a direct call to super() in C(), and call to this() in C(String s). So eventually, super() will directly happen. In C(int i) we have nothing, so as I quoted: "the compiler will insert the no-arg call to super()".
Ok, I got confused with this question as well
Now, that I have thoroughly investigated the options and the given explanation, I see that there is nothing wrong with the question. You are right that default constructor of B will be invoked. But you are wrong that B does not have a default constructor. Since there is no explicitly defined constructor in B, the compiler will provide one automatically.
HTH,
Paul.
If you like our products and services, please help us by posting your review here.