Reputation: 589
I know that in case of Inheritance the subClass constructor should call the superClass constructor explicitly if the default constructor in the superClass is missing
but when chaining to another constructor in the subClass why we don't have to call the superClass Constructor then? as the code below is not giving a compilation error
SuperClass:
public class Top {
public Top(String n) {
// TODO Auto-generated constructor stub
}
SubClass:
public class sub extends Top {
public sub(int x){
super("");
}
public sub(String x) {
this(5);
}
}
Upvotes: 1
Views: 71
Reputation: 72844
Because the "chained" constructor will call the superclass constructor itself. Otherwise you would be calling the superclass constructor twice (hence the effects of the parent class' constructor will execute twice which may cause an inconsistent behavior, e.g. calling instance initializers twice). More formally, the sequence of constructor calls is explained in this section of the Java Language Specification:
Assign the arguments for the constructor to newly created parameter variables for this constructor invocation.
If this constructor begins with an explicit constructor invocation (§8.8.7.1) of another constructor in the same class (using
this
), then evaluate the arguments and process that constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason; otherwise, continue with step 5.This constructor does not begin with an explicit constructor invocation of another constructor in the same class (using
this
). If this constructor is for a class other thanObject
, then this constructor will begin with an explicit or implicit invocation of a superclass constructor (usingsuper
). Evaluate the arguments and process that superclass constructor invocation recursively using these same five steps. If that constructor invocation completes abruptly, then this procedure completes abruptly for the same reason. Otherwise, continue with step 4....
Notice that step 2 is recursive and applies to the constructor that calls the other constructor in the subclass. And step 3 applies to the constructor that calls the parent class' constructor.
Upvotes: 2
Reputation: 83
if the constructors had to match exactly for all subclasses, and that subclass had to call the matching constructor, it wouldnt leave much room for change. As long as the subclass eventually calls one of the superclasses constructors, everything is fine.
Upvotes: 0