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.
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
You take name放在父类Base中定义就不会报错。 因为你实例化Sub时,会调用默认的构造函数,默认的构造函数会调用父类的构造函数,在父类的构造函数中,你使用了test()方法,而你在子类中重写了该方法,子类的test方法内使用了name,但是这时候name还没有完成初始化。所以会报NullPointerException.
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 class
static{...}
Static members of parent class
Parent class construction method
Subclass
static{...}
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 processParent class initialization process> Subclass initialization process
test()
方法时,子类的name
还没有赋值,仍然是null
So during your instantiation process, if you call the parent class constructor and callYou take
name
放在父类Base
中定义就不会报错。 因为你实例化Sub
时,会调用默认的构造函数,默认的构造函数会调用父类的构造函数,在父类的构造函数中,你使用了test()
方法,而你在子类中重写了该方法,子类的test
方法内使用了name
,但是这时候name
还没有完成初始化。所以会报NullPointerException
.