Can an instance method be called from an initialization block?

I was combing Java and I read that "initializer block can call methods"

Can it call instance methods even though the constructor did not execute? Is it just frowning?

EDIT: I can see that the compiler allows this, so the question is, is this a good safe practice?

+3


source to share


1 answer


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?

+2


source







All Articles