This is just going to be another rambling about an inconvenient situation that occurs often in Java. Nothing concrete, no plans of mine to do anything about it any time soon.
Constructors are quite special: They can initialize final
fields. You may call another method, a special method only called in the constructor, yet in that method, final
methods cannot be initialized anymore. Such a method would be tremendously useful to increase code reuse:
class A {
private final Object _something = null;
public A() {
/* do something */
}
public A(Object o) {
/* do something */
_something = o;
}
}
It would be nice to get the /* do something */
factored out into a method. In this case, of course, a this()
call can help:
class A {
private final Object _something = null;
public A() {
/* do something */
}
public A(Object o) {
this();
_something = o;
}
}
The situation I ran into now is similar, except that I had a super class and needed to make a super()
call as well:
class S {
protected final Object _something = null;
public S() { }
public S(Object o) {
_something = o;
}
}
class A extends S{
public A() {
/* do something */
}
public A(Object o) {
super();
this(); // error: this() must be first statement
}
}
If I still want to use this()
to factor code out, I have to put the super()
call second, that’s not allowed, and vice versa.
Besides removing some restrictions for methods called from the constructor, are there any good reasons why this()
could not be called after the super()
call?
One Response to
this()
vs.super()