activity - Android中抽象方法赋值时出现null.
阿神
阿神 2017-04-17 17:49:13
0
1
423

首先先声明两个类

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,请问是我哪里理解错误了.

阿神
阿神

闭关修行中......

reply all(1)
巴扎黑

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 in Main2Activity needs to be assigned an initial value, and the initial value comes from the getStudent() method, so this method is be executed. However, during the execution of this method, the Person person in the MainActivity used has not yet been assigned an initial value, and it is still null, so The person referenced in getStudent() is null, which leads to the subsequent call of getA() What is returned is null. 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中引用的PersonThe assignment of Person person in MainActivity is done in the subclass, that is, after the initialization operation of Main2Activity is completed. At this time, Student B has already been assigned a value, so if you assign a value to Person person at this time, the Person referenced in Student B cannot be changed. .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template