GDGDJKJ
GDGDJKJ

Reputation: 209

Add an object to another object contained in one of the first's class attributes, Java

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

Upvotes: 0

Views: 698

Answers (1)

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

Use this to reference this instance. It's not only a way to access properties and methods, but also a reference.

person.setClub(this);

Upvotes: 2

Related Questions