Why is it not recommended to call the Set method from the constructor?

Is this true only in inheritance or in most cases?

public class MyClass {
   public int id;

     public MyClass() {
         // Some stuff 
         setId(5);
     }

     public setId(int id) {
         this.id = id;
     }
}
+4
source share
6 answers

It's true.

Because setters are always public. And if you are not a class final, then there is the problem of invoking the alien method. Which is not thread safe, i.e. It is known as link escaping this. Therefore, from the constructor, if you call a method, it should be finalor private. Else safe initializationobject will not happen, which causes many errors in real systems.

, public constructor, , , , .

, . , . , , , .

.

+6

.

, , , .

,

class MyClass {
    public int id;
    protected String someStr;

    public MyClass() {
        SetId(5);
        someStr = "test";
    }

    public void SetId(int Id) {
        id = Id;
    }
}

MyClass SetId, someStr, , , NullPointerException.

class MySubClass extends MyClass {

    public void SetId(int Id) {
       id = Id;
       someStr.toString(); // will cause NullPointerException
    }
}

NPE , .

+3

setter, , .

public class MyClass {
    int id; 
    public MyClass() { 
        id=5;   
    }
}

/ .

, .

[]

, .

Java - Subclass supers,

+3

, , , , " ". SetId , , . , SetId /infothat, , .

, " , "

+2

, , . setName (...) , - setName (...). ( ) . , . : ,

+1

Java , ctor , .

SetId, MyClass final private.

0

All Articles