When do you call super() in Java? I see it in some constructors of the derived class, but isn\'t the constructors for each of the parent class called automatically? Why woul
I wanted to provide some information that hasn't been mentioned so far. If you use a call to this(...)
in a constructor, then you can't have a call to super(...);
This also includes Java's automatic insertion of the parameterless call to super();
The following example illustrates this point, including explanatory comments:
public class B extends A {
private int x;
public B() {
// Java doesn't call super(); here, because
// of the call to this(...); below.
// You can't call super(...) here either,
// for the same reason.
this(42); // Calls public B(int x) below.
}
public B(int x) {
// Java does call super(); here.
// You can call super(...) here, if you want/need to.
// The net result of calling new B() above is that
// super(...) for class A only gets called once.
this.x = x;
}
}