Hi All,
while Im doing mock exams i found a question on inheritence constructors... by seeing that i totally forgot all my knowledge on inheritence... the question is
class Base
{
Base()
{
System.out.println("Message 1 : In the base class constructor");
}
}
abstract class Derived1 extends Base
{
Derived1()
{
System.out.println("Message 2 : In the abstract class Derived1\'s constructor");
}
}
public class Derived2 extends Derived1
{
public Derived2()
{
System.out.println("Message 3 : In the derived2 class\'s constructor.");
}
public static void main(
String args[])
{
Derived2 d2 = new Derived2();
}
}
An attempt to compile and run the above code
1) will cause a compiler error. The non-abstract classes cannot be extended to the abstract classes.
2) will cause a compiler error. The abstract classes cannot have constructors defined.
3)will not cause any compiler error. The lines "Message 1..." and "Message 3 ... " are printed on the screen.
4)will not cause any compiler error. The lines "Message 1..." and "Message 2...." and Message 3...." are printed on the screen.
The answer is 4,its correct i tested,the problem is --why base class constructors are called when calling a derived class constructor,then whats the use of super().
please help me.
Regards,
Deepak.