Is it true only in Inheritance or most of the cases ?
public class MyClass {
public int id;
public MyClass() {
// Some stuff
setI
It is very true.
Because setters are always public
methods. And if you class is not final
then there is issue of alien method call. Which is not thread safe i.e. it is known as escaping of this
reference. So from a constructor if you are calling a method it should be final
or private
. Else safe initialization
of object will not happen which causes many bugs in real systems.
Apart from the above we should never call public
method from the constructor
because if the class is intended for inheritance than Constructors must not invoke overridable methods, directly or indirectly.
If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
source.