Why is the value of the instance field coming null?

前端 未结 3 930
天命终不由人
天命终不由人 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 19:49

    The object is null because The superclass constructor runs before the subclass constructor,hence it would only be natural that the statement Object obj = null; is executed after calling super class constructor.

    The assignment of Object obj = null; is inlined into the constructor during compile time. This are only accessible in existing instance, and instance does not exist yet when you are in constructor (it is still under construction).

    You can achieve object value(Object = java.lang.Object@3cd1a2f1) by declaringobject object as static.

    static Object obj = null;

    Generally though, it's bad practice to call overriden methods from a constructor in real time.

提交回复
热议问题