Can an instance method be called from an initialization block?
The instance initializer block will be called as part of the execution of any constructor. So you can see it as if it was copied into each constructor by the compiler.
This simplifies your question: is it the same as asking "Is it safe practice to call instance methods from a constructor?"
As long as the method you are calling cannot be overridden in the subclass, this is perfectly fine. Therefore, if your method is private
or final
, there is no problem.
In these cases, it is preferable to have a copying method in the same or similar code.
The problem arises when a subclass can override a method, because then you call that method from the constructor, but the subclass's constructor hasn't been executed yet. And this method will try to access fields that have not yet been initialized.
More details: What's wrong with overridden method calls in constructors?
source to share