From Effective Java 2nd edition, item 17:
For each public or protected method or constructor, the documentation must indicate which overridable methods the method or constructor invokes
Later in the same item it says:
Constructors must not invoke overridable methods, directly or indirectly.
Aren't these two statements contradictory, or am I missing something?
Invoking overridable methods during construction is Allowed - there is nothing illegal about this.
Invoking overridable methods during construction is NOT Advisable - It is generally ill-advised to invoke overridable methods during construction because this can cause incomplete objects to be exposed and restricts the predictability of the system.
public class A {
final int a;
public A() {
a = method();
}
protected int method() {
return 42;
}
@Override
public String toString() {
return "A{" + "a=" + a + '}';
}
}
public class B extends A {
@Override
protected int method() {
System.out.println("this=" + this);
return 96;
}
}
public void test() {
System.out.println("B = " + new B());
}
Note that your first quote only refers to the documentation, not the code. I would suggest the only issue is the use of must when should would probably be more appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With