9

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
traveh
  • 2,700
  • 3
  • 27
  • 44
  • You can read it in a sense which is non-contradictory: it can be vacuuosly true a constructor's documentation indicates all overridable methods invoked, if there are zero overridable methods invoked. But I suspect that's not the spirit in which it was written, nor the one that you are meaning :) – Andy Turner Apr 06 '16 at 13:53
  • Not really, you should document which overridable members you invoke, just so somebody can override them, and afterwards can 't say > "hey, but you never informed me overriding this or that wouldn't have > any side effects" That aside, there always will be people changing methods in their (overriden) classes, which might break your code, so it is best never to do this. – Stultuske Apr 06 '16 at 13:54

1 Answers1

1

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.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213