Why is the value of the instance field coming null?

前端 未结 3 1026
天命终不由人
天命终不由人 2021-01-23 19:29

I have this simple piece of code.

abstract class X {
    X() {
        read();
    }

    private void read() {
        Object obj = new Object();
        readVa         


        
3条回答
  •  天命终不由人
    2021-01-23 20:07

    The reason the obj field is null is due to the sequence of steps that occur in the constructor call of Y:

    1. The constructor of Y calls the super constructor which eventually calls readValue of the concrete class Y, therefore assigning a non-null value to the obj field.
    2. After the super constructor finishes, the instance field obj is initialized to null due to the variable initializer:

      Object obj = null;
      

    When you remove the null initializer, it becomes a simple field declaration with no instance initialization to be performed in step 2.

    The apt solution is not to remove the null initializer, but to re-design the whole class hierarchy. For example, since the purpose of readValue seems to just be a setter for a variable, then you don't need to make it override an abstract method in the parent class. Just set it as a separate method and call it after the constructor of Y completes.

提交回复
热议问题