Matt
Matt

Reputation: 11327

Not sure how to find this object instance

I'm learning OOP in Java, but I'm not sure how to implement this reference or whatever you want to call it.

There are two relevant classes: Manager and Team

Team contains a field called manager, which is an instance of Manager. This links the team to a manager. It also contains a String field called name, which is the teams name.

Manager contains a String field called name, which is the managers name. It also contains a method called printDetails() which is supposed to print the managers name and team name. The bit I'm stuck with is finding the Team instance for this Manager so I can get her teams name.

I haven't posted any code because I think this is a design feature, and there isn't some magical code to do it for me. (unless you can iterarte through all the Team instances to find the manager)

Upvotes: 1

Views: 133

Answers (5)

zerodin
zerodin

Reputation: 877

Since "Team" contains a reference to "Manager", it can call a method on "Manager" to set the name of the team.

Upvotes: 0

Alex Rashkov
Alex Rashkov

Reputation: 10015

class Manager() {
  private Team team;
  private string name;
  private int age;
  public function void Manager(Team t) {
    this.team = t;
  }
}

class Team() {
  private string teamName;
  ...
}

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

If a Manager manages a single team, you can define a field member in Manager class called teamName and set it to the team's name

Upvotes: 0

Skilldrick
Skilldrick

Reputation: 70849

If the Manager needs to know about the Team, then Team can pass this to Manager in its constructor.

Also, you need to think about who owns who. Does the manager own a team, or does the team own a manager? Maybe in this example, it would be better if Manager had a Team, so it could easily get the details of its team.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500725

Two options:

  • Give the Manager a reference to the Team too
  • Keep a list of all the teams, so you can look through to find which one has the given manager

Upvotes: 3

Related Questions