如何修改属于另一个私有嵌套类的私有嵌套类的最终成员?

问题描述 投票:0回答:0

我有下一个代码:

public class NotesCollection {
    private Notes[] notesCollection;

    private static class Notes {
        private final Person person;
        private String info;
        
        private Notes(Person person, String info) {
            this.person = person;
            this.info = info;
        }

        private static class Person {
            private String firstName;
            private String lastName;

            private Person(String firstName, String lastName) {
                this.firstName = firstName;
                this.lastName = lastName;
            }
        }
         
            public boolean create(String firstName, String lastName, String info) {
            // should create new element in the array 'notesCollection'
            }

    }
}

我的方法 create() 有问题。为了调用“Notes”类的构造函数,我之前应该有一个 Person 的实例,因为字段“Person person”是最终的,所以我只能在那个构造函数中初始化它,因为这样的代码不起作用

 public boolean create(String firstName, String lastName, String info) {
         Notes notes = new Notes(null, info);
         notes.person = new Notes.Person(firstName, lastName); // error

我不能那样做

 public boolean create(String firstName, String lastName, String info) {
       Person person = new Notes.Person(firstname, lastname); // error
}

那我可以在这里做什么?将感谢任何建议。

java constructor inner-classes final
© www.soinside.com 2019 - 2024. All rights reserved.