0

I've been reading Joshua Bloch's Effective Java and it states clearly that non-final methods should not be called inside a constructor and I understand why calling them can be a problem.

My surprise has been when reading openjdk code and seeing that, in the "copy constructor" for LinkedList, non-final method addAll (inherited from AbstractCollection) is called.

If the Java writers themselves do this, there must be circumstances in which doing it is safe. When is it safe to do so? If I define another collection class, am I allowed to call addAll in a constructor?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Juan Manuel
  • 355
  • 1
  • 7

1 Answers1

1

Good question. Simply put, you can under some circumstances, only if the overridden method does not depend on the initialization of the child class. In the example underneath, the output is 0, because the childvar variable has been created, but both the line assigning the initial value int childvar=1 and the assignment in the Child constructor have not been executed yet. On the other hand, you can if you only use the Parent environment. It can lead to unexpected results, hard to debug errors, so I suggest you only use it if it really saves a lot of time and be careful, this is tricky.

abstract class Parent {
  protected int parentvar = 2;

  public Parent() {
    invokeMethod();
  }

  public abstract void invokeMethod();

   public static void main(String[] args) {
      new Child();
   }
}

class Child extends Parent {
  protected int childvar = 1;

  public Child() {
     super();
     childvar = 2;
  }

  public void invokeMethod() {
     System.out.println("" + childvar);
  }
}
Jeroen Vuurens
  • 1,171
  • 1
  • 9
  • 10