有人跟我讲,将name进行静态赋值即可,但实例变量不也是属于成员变量吗,也是在整个类实例化的时候产生的啊,跟静态赋值有何区别吗?
伊谢尔伦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()
。
将name
If 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
巴扎黑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
还没有赋值,仍然是null
So during your instantiation process, if you call the parent class constructor and call
高洛峰2017-04-18 10:52:14
You take name
放在父类Base
中定义就不会报错。 因为你实例化Sub
时,会调用默认的构造函数,默认的构造函数会调用父类的构造函数,在父类的构造函数中,你使用了test()
方法,而你在子类中重写了该方法,子类的test
方法内使用了name
,但是这时候name
还没有完成初始化。所以会报NullPointerException
.