To make this question clear, I show it in an example.
I have a simple class called Player, which contains three data members( "attack" which is important here), and have setters and getters for them. (only setAttack() which matters now). I have a "Team" class which will contain three Player objects, to make some operation on Players' fields. Also, Team class has a simple method named increaseattack(), which will increase a specific players attack by 1. (immediately called when Team object created through its constructor). In Match class I create 3 player objects, and a team object made by those. And now the fun starts: calling setAttack() inside Team class for the specified player will also change the originally created player's attack in Match class!
I know that I am wrong about somewhat basic conception, but do not know how Its properly done. Could you explain it to me, why is this working like that? Here is the source of the three classes:
public class Player {
String name;
int attack;
int defense;
public Player(String name, int attack, int defense){
this.name = name;
this.attack = attack;
this.defense = defense;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getDefense() {
return defense;
}
public void setDefense(int defense) {
this.defense = defense;
}
}
public class Team {
private Player player1;
private Player player2;
private Player player3;
public Team(Player p1, Player p2, Player p3){
this.player1 = p1;
this.player2 = p2;
this.player3 = p3;
increaseattack(player1);
}
public void increaseattack(Player pla){
pla.setAttack(pla.getAttack()+1);
}
}
public class Match {
Player player, player2, player3;
Team team, team1;
//static Player player, player2, player3;
//static Team team, team1;
public static void main(String[] args){
new Match();
}
public Match(){
test();
}
public void test() {
player = new Player("Alan", 10, 10);
player2 = new Player("Bob", 10, 12);
player3 = new Player("Cedric", 13, 10);
team = new Team(player,player2,player3); // Creating the team instance based on player instances created here, OK 10+1 = 11
team1 = new Team(player,player2,player3); // new team, hopefully i get the same results, but thats not the case, 11 is base attack, not 10!!!
System.out.println("------------------------");
System.out.println(" " + player.getName() + " " + player.getAttack() + " " + player.getDefense());
System.out.println(" " + player2.getName() + " " + player2.getAttack() + " " + player2.getDefense());
System.out.println(" " + player3.getName() + " " + player3.getAttack() + " " + player3.getDefense());
}
}
Here's the output:
------------------------
Alan 12 10
Bob 10 12
Cedric 13 10
Which is not correct for me, as I expected Alan's original attack has not changed, only "in" the team. I appreciate any help. Thank you.