首先先声明两个类
public class Person {
.....
}
public class Student {
public Person A;
public Student(Person a) {
A = a;
}
.....
}
MainActivity
在实现抽象activity
时出现空的返回值
public abstract class Main2Activity extends AppCompatActivity{
Student B = getStudent();
oncreate(...){
......
getStudent().getA();
//A不为null
B.getA();
//A为null
}
public abstract Student getStudent();
}
MainActivity
public class MainActivity extends Main2Activity{
Person person = new Person(10);
@Override
public Student getStudent() {
Student student = new Student(person);
return student;
}
}
为什么会出现成员变量A为null
的情况,但是在声明周期中赋值时并不会出现这个问题.两种情况下成员变量B
都不会是null
,请问是我哪里理解错误了.
This is a problem with the order of parameter assignment during class initialization.
When the subclass, that is,
MainActivity
is initialized, the parent class, that is,Main2Activity
, will be initialized first. At this time,Student B
defined inMain2Activity
needs to be assigned an initial value, and the initial value comes from thegetStudent()
method, so this method is be executed. However, during the execution of this method, thePerson person
in theMainActivity
used has not yet been assigned an initial value, and it is stillnull
, so Theperson
referenced ingetStudent()
isnull
, which leads to the subsequent call ofgetA()
What is returned isnull
.MainActivity
初始化时,首先会初始化父类,也就是Main2Activity
。这时候Main2Activity
中定义的Student B
就需要赋初值了,而初始值来自getStudent()
这个方法,于是这个方法就被执行。可是在这个方法执行的过程中,使用的MainActivity
中的Person person
其实还没有赋初值,其仍然还是null
,所以getStudent()
中引用的person
就是null
,这也就导致了后面调用getA()
的时候返回的是null
。MainActivity
中的Person person
的赋值,是在子类,也就是Main2Activity
初始化操作完成之后的,这个时候Student B
已经进行了赋值,所以这时候再对Person person
进行赋值,其实不能改变Student B
中引用的Person
The assignment ofPerson person
inMainActivity
is done in the subclass, that is, after the initialization operation ofMain2Activity
is completed. At this time,Student B
has already been assigned a value, so if you assign a value toPerson person
at this time, thePerson
referenced inStudent B
cannot be changed. .