Why is it considered bad practice in Java to call a method from within a constructor?
First, in general there's no problem with calling methods in a constructor. The issues are specifically with the particular cases of calling overridable methods of the constructor's class, and of passing the object's this
reference to methods (including constructors) of other objects.
The reasons for avoiding overridable methods and "leaking this
" can be complicated, but they basically are all concerned with preventing use of incompletely initialised objects.
Avoid calling overridable methods
The reasons for avoiding calling overridable methods in constructors are a consequence of the instance creation process defined in §12.5 of the Java Language Specification (JLS).
Among other things, the process of §12.5 ensures that when instantiating a derived class[1], the initialisation of its base class (i.e. setting its members to their initial values and execution of its constructor) occurs before its own initialisation. This is intended to allow consistent initialisation of classes, through two key principles:
- The initialisation of each class can focus on initialising only the members it explicitly declares itself, safe in the knowledge that all other members inherited from the base class have already been initialised.
- The initialisation of each class can safely use members of its base class as inputs to the initialisation of its own members, as it is guaranteed they've been properly initialised by the time the initialisation of the class occurs.
There is, however, a catch: Java allows dynamic dispatch in constructors[2]. This means that if a base class constructor executing as part of the instantiation of a derived class calls a method that exists in the derived class, it is called in the context of that derived class.
The direct consequence of all of this is that when instantiating a derived class, the base class constructor is called before the derived class is initialised. If that constructor makes a call to a method that is overridden by the derived class, it is the derived class method (not the base class method) that is called, even though the derived class has not yet been initialised. Evidently this is a problem if that method uses any members of the derived class, since they haven't been initialised yet.
Clearly, the issue is a result of the base class constructor calling methods that can be overriden by the derived class. To prevent the issue, constructors should only call methods of their own class that are final, static or private, as these methods cannot be overridden by derived classes. Constructors of final classes may call any of their methods, as (by definition) they cannot be derived from.
Example 12.5-2 of the JLS is a good demonstration of this issue:
class Super {
Super() { printThree(); }
void printThree() { System.out.println("three"); }
}
class Test extends Super {
int three = (int)Math.PI; // That is, 3
void printThree() { System.out.println(three); }
public static void main(String[] args) {
Test t = new Test();
t.printThree();
}
}
This program prints 0
then 3
. The sequence of events in this example is as follows:
new Test()
is called in themain()
method.- Since
Test
has no explicit constructor, the default constructor of its superclass (namelySuper()
) is called. - The
Super()
constructor callsprintThree()
. This is dispatched to the overriden version of the method in theTest
class. - The
printThree()
method of theTest
class prints the current value of thethree
member variable, which is the default value0
(since theTest
instance hasn't been initialised yet). - The
printThree()
method andSuper()
constructor each exit, and theTest
instance is initialised (at which pointthree
is then set to3
). - The
main()
method callsprintThree()
again, which this time prints the expected value of3
(since theTest
instance has now been initialised).
As described above, §12.5 states that (2) must happen before (5), to ensure that Super
is initialised before Test
is. However, dynamic dispatch means that the method call in (3) is run in the context of the uninitialised Test
class, leading to the unexpected behaviour.
Avoid leaking this
The restriction against passing this
from a constructor to another object is a little easier to explain.
Basically, an object cannot be considered fully initialised until its constructor has completed execution (since its purpose is to complete the initialisation of the object). So, if the constructor passes the object's this
to another object, that other object then has a reference to the object even though it hasn't been fully initialised (since its constructor is still running). If the other object then attempts to access an uninitialised member or call a method of the original object that relies on it being fully initialised, unexpected behaviour is likely to result.
For an example of how this can result in unexpected behaviour, please refer to this article.
[1] Technically, every class in Java except
Object
is a derived class - I just use the terms 'derived class' and 'base class' here to outline the relationship between the particular classes in question.[2] There's no reason given in the JLS (as far as I'm aware) as to why this is the case. The alternative - disallowing dynamic dispatch in constructors - would make the whole issue moot, which is probably exactly why C++ doesn't allow it.
Constructors should only ever call methods that are private, static or final. This helps get rid of the issues that can appear with Overriding.
Also, Constructors shouldn't start threads. There are two problems with starting a thread in a constructor (or static initializer):
- in a non-final class, it increases the danger of problems with subclasses
- it opens the door for allowing the this reference to escape the constructor
There's nothing wrong with creating a thread object in a constructor (or static initializer) - just don't start it there.
Calling instance method in constructor is dangerous as the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on test-ability.
Just be careful when doing, its bad practice to do it with override able methods.