java - 请问下,这里为何会引发空指针异常?
黄舟
黄舟 2017-04-18 10:50:14
0
3
524

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

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(3)
伊谢尔伦

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

巴扎黑

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. 🎜
小葫芦

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!