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

前端 未结 6 1402
梦毁少年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:37

    You should not call an overridable method from a constructor.

    If you call a method that can be overridden by a subclass in a costructor, than the subclass might access variables of the superclass that have not been initialized yet.

    For example the following code looks good so far

    class MyClass {
        public int id;
        protected String someStr;
    
        public MyClass() {
            SetId(5);
            someStr = "test";
        }
    
        public void SetId(int Id) {
            id = Id;
        }
    }
    

    If you now subclass MyClass and override the SetId method you might access the superclass's someStr variable which has not been initialized yet and thus will cause a NullPointerException in this case.

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

    The cause of the NPE might be hard to see if there is a bigger inheritence hierarchy.

提交回复
热议问题