Consider there are three classes A, B and C. Class A doesn't have a constructor, ClassB has a constructor and Class C has a parameterized constructor. something like the example given below.
public class ClassA {
}
public class ClassB extends ClassA {
public ClassB() {
System.out.println("Default cons Class B");
}
}
public class ClassC extends ClassB {
public ClassC(int a, int b) {
System.out.println("This is class C "+a+ "and"+ b );
}
public static void main(String args[]) {
ClassC c = new ClassC(2,3);
}
}
Output:
Default cons Class C
This is class C 2and3
Question 1:
To construct object C it constructs B and to construct B it constructs A first. Even though there isn't any default constructor in class A defined, the program works fine by construction its own default constructor and the B class calls super(). I don't have an issue here however when I change the Class B something like this
public class ClassB extends ClassA {
public ClassB(int a, int b) {
System.out.println("This is class C "+a+ "and"+ b );
}
}
I am getting an error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor ClassB() is undefined. Must explicitly invoke another constructor
at ClassC.<init>(ClassC.java:4)
at ClassC.main(ClassC.java:10)
Why do we have to implicitly specify the super constructor ClassB(), It worked fine for the first example even though there isn't any super constructor in ClassA(). I am wondering if by default the C's constructor by default calls B's unspecified constructor just like it did for Class A.