无法访问内部类值

时间:2019-05-21 15:08:44

标签: java

我有一个内部类,如图所示

public class Student {
    private String studentName;
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public class StudentInnerClass {
        private String addressCity;

        public String getAddressCity() {
            return addressCity;
        }
        public void setAddressCity(String addressCity) {
            this.addressCity = addressCity;
        }
    }

}

我正在尝试如图所示访问内部类的值,但是该值将为null

 public class Test {
    public static void main(String[] args) {
        List<Student> studentsVOList = new  LinkedList<Student>();
        Student studentOuter = new Student();
        Student.StudentInnerClass studentInner =  studentOuter. new StudentInnerClass();
        studentOuter.setStudentName("Jai");
        studentInner.setAddressCity("HYD");
        studentsVOList.add(studentOuter);
        for(Student VOObject : studentsVOList) {
            Student student = (Student) VOObject;
            Student.StudentInnerClass studInn =student.new StudentInnerClass();  
            System.out.println(studInn.getAddressCity());
        }
    }
}

当我运行程序时,studInn.getAddressCity()为空

1 个答案:

答案 0 :(得分:0)

在您的Student类中,您仅定义了一个内部类;而不是用于存储此类的内部对象的字段。内部类有其自己的状态,外部类的对象不能隐式引用它们的实例。如果要让Student外部类保留对内部类对象的引用,则必须显式声明它:

    public static class Student {
        private String studentName;
        private StudentInnerClass innerObject = new StudentInnerClass();

        public StudentInnerClass getInnerObject() {
            return innerObject;
        }

        public void setInnerObject(StudentInnerClass innerObject) {
            this.innerObject = innerObject;
        }

...

然后,每次实例化Student类时,将使用一个名为innerObject的属性来访问所需的内部对象。最后,您可以使用它来设置和获取addressCity属性,

        student.getInnerObject().setAddressCity("HYD");
        student.getInnerObject().getAddressCity();

希望这会有所帮助。