mc20 mc20 - 2 months ago 10
Java Question

Sharing of Model object across classes

I have a model class

Team
. I need to perform multiple operations on this class in different classes like
Coach
and
Admin
. My question is how do I maintain once same
Team
object while creating all other classes.??

In the
TestDriver
class , I have used the team object to create
Coach
initially. But if I want to create new
Admin
,I need to pass the same
Team
. Is there any pattern I need to follow here.?

//Model Classes

public class Player {
String playerName;
}

public class Team {
List<Player> playerList;
}


//Class to modify model

public class Coach {
Team team;

public Coach ( Team team) {
this.team = team;
}

public void deletePlayer(Player) {
//Remove the player form team
}
}

public class Admin {
Team team;

public Admin ( Team team) {
this.team = team;
}

public void addPlayer(Player) {
//Add the player to team
}
}

//Test Driver class

public class TestDriver {
public static void main(String args[]) {

Team team = new Team();

Coach coach = new Coach(team);
coach.deletePlayer(team);

//How to pass the same team
Admin admin = new Admin(???);
admin.addPlayer(team);

}
}

Answer

This will do :Admin admin = new Admin(team);

Now both the admin and coach instance will be referring to the same team instance. So whatever changes you make to the team in one will reflect in the other.

You should read more about how in Java the variables are only holding the references to actual object in memory.

Comments