Why it is not a good idea to call Set method from constructor?

前端 未结 6 1366
梦毁少年i
梦毁少年i 2020-12-18 09:57

Is it true only in Inheritance or most of the cases ?

public class MyClass {
   public int id;

     public MyClass() {
         // Some stuff 
         setI         


        
6条回答
  •  醉梦人生
    2020-12-18 10:40

    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.

提交回复
热议问题