I've been brushing up on Java and I've read that "initializer block can call methods"
Can it call instance methods despite the constructor not having executed? Is this just frowned upon?
EDIT: I see the compiler allows it, so the question is, is it a good, safe practice?
An 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 every constructor by the compiler.
That makes your question simpler: it is the same as asking: "is it a safe practice to call instance methods from a constructor?"
As long as the method you are calling cannot be overridden in a subclass, this is completely fine.
So if your method is private
or final
, there's no issue.
In those cases, it's preferable to have a method over copy-pasting the same or similar code.
The problem occurs when a subclass could override a method, because then you would invoke that method from the constructor, but the subclass constructor hasn't executed yet. And the method would be trying to access fields that are not initialized yet.
For more detail: What's wrong with overridable method calls in constructors?