Home  >  Q&A  >  body text

java - 请问下,这里为何会引发空指针异常?

有人跟我讲,将name进行静态赋值即可,但实例变量不也是属于成员变量吗,也是在整个类实例化的时候产生的啊,跟静态赋值有何区别吗?

黄舟黄舟2743 days ago521

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:52:14

    The constructor of the parent class is executed before the constructor of the subclass. Base()->test()-->name.length()相当于null.length()
    nameIf it is written as static, of course it is OK, because the initialization of static members precedes the initialization of instance members.

    The order is roughly as follows:

    • Parent classstatic{...}

    • Static members of parent class

    • Parent class construction method

    • Subclassstatic{...}

    • Subclass static members

    • Subclass construction method

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 10:52:14

    First throw out a concept, the initialization process of an object:
    Static variable> Static initialization block> Instance variable> Constructor静态变量 > 静态初始化块 > 实例变量 > 构造器
    而存在父子类关系的对象,又存在一个嵌套的初始化流程
    父类初始化流程 > 子类初始化流程And objects with a parent-child class relationship also have a nested Initialization process

    Parent class initialization process> Subclass initialization process

    test()方法时,子类的name还没有赋值,仍然是nullSo during your instantiation process, if you call the parent class constructor and call

    , a null pointer will naturally be reported. 🎜

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 10:52:14

    You take name放在父类Base中定义就不会报错。 因为你实例化Sub时,会调用默认的构造函数,默认的构造函数会调用父类的构造函数,在父类的构造函数中,你使用了test()方法,而你在子类中重写了该方法,子类的test方法内使用了name,但是这时候name还没有完成初始化。所以会报NullPointerException.

    reply
    0
  • Cancelreply