Sunday, 26 March 2017

java - Why do this() and super() have to be the first statement in a constructor?

Java requires that if you call this() or super() in a constructor, it must be the first statement. Why?



For example:




public class MyClass {
public MyClass(int x) {}
}

public class MySubClass extends MyClass {
public MySubClass(int a, int b) {
int c = a + b;
super(c); // COMPILE ERROR
}

}


The Sun compiler says "call to super must be first statement in constructor". The Eclipse compiler says "Constructor call must be the first statement in a constructor".



However, you can get around this by re-arranging the code a little bit:



public class MySubClass extends MyClass {
public MySubClass(int a, int b) {
super(a + b); // OK

}
}


Here is another example:



public class MyClass {
public MyClass(List list) {}
}


public class MySubClassA extends MyClass {
public MySubClassA(Object item) {
// Create a list that contains the item, and pass the list to super
List list = new ArrayList();
list.add(item);
super(list); // COMPILE ERROR
}
}

public class MySubClassB extends MyClass {

public MySubClassB(Object item) {
// Create a list that contains the item, and pass the list to super
super(Arrays.asList(new Object[] { item })); // OK
}
}


So, it is not stopping you from executing logic before the call to super. It is just stopping you from executing logic that you can't fit into a single expression.



There are similar rules for calling this(). The compiler says "call to this must be first statement in constructor".




Why does the compiler have these restrictions? Can you give a code example where, if the compiler did not have this restriction, something bad would happen?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...