An elementary concept in constructors is that any call to super() or this() must be the first line in the constructor. Obviously, this means you can have only one. The following will not compile.
public class foo{
public static void main(
String[] args) {
bar mybar = new bar();
}
}
class bar extends foo{
private String name;
bar(String s) {
name = s;
}
bar(){
super();
this("default");
}
}
Why exactly? If I had the following:
bar(){
this("default");
}
the compiler would automatically put in a call to super, specifically a call to the no args constructor. Why by rule can we not do this manually? The bit of web research I did just asserted the elementary rule I talked about up top, and my book just asserts it as well. It doesn't seem to me like it would violate constructor chaining. What *would* do that would be allowing something like:
bar() {
this("default");
super();
}
Now that would cause a headache! Did the designers of
Java just put in the rule this() or super()
must be first to make it an easier language to implement, or am I missing something deeper?
Thanks.
Since a call to the no-args super constructor is automatically inserted by the compiler