将一个对象添加到第一个对象的类属性中包含的另一个对象中,Java。

huangapple go评论73阅读模式
英文:

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);

huangapple
  • 本文由 发表于 2020年4月4日 19:38:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/61027507.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定