Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When planning for inheritance, are constructers allowed to call overridable method?

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?

like image 448
traveh Avatar asked Apr 06 '16 13:04

traveh


1 Answers

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.

like image 178
OldCurmudgeon Avatar answered Sep 22 '22 19:09

OldCurmudgeon