英文:
Add an object to another object contained in one of the first's class attributes, Java
问题
我有一个名为Club的类,其中包含一个人的ArrayList,这些人是对象。每个人都有一个名为club的属性,属性类型为Club。为了将人员添加到俱乐部,我已经创建了一个名为addMember的方法,它接受一个Person对象,并将其添加到所需的ArrayList中。
是否可能像这样做?
public class Club {
...
public void addMember(Person person) {
person.setClub(**这个俱乐部的实例**);
this.memberList.add(person);
}
...
}
英文:
I have a class called Club that contains an ArrayList of persons, which are objects. Each Person has a club attribute of type Club. To add persons to the club, I have made a method, addMember, that takes a Person object and adds it to the desired ArrayList.
Is it possible to do something like this?
public class Club {
...
public void addMember(Person person) {
person.setClub(**This instance of club**);
this.memberList.add(person);
}
...
}
答案1
得分: 2
使用this
来引用当前实例。这不仅是访问属性和方法的一种方式,还是一个引用。
person.setClub(this);
英文:
Use this
to reference this instance. It's not only a way to access properties and methods, but also a reference.
person.setClub(this);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论