mercredi 31 août 2022

How to restrict access privilege between two classes in java?

I have two classes Player and Game

public class Player {
    private List<String> cards;

    public Player(){
        cards = new ArrayList<String>();
    }
}
public class Game {
    List<Player> players;

    public Game(List<Player> players){
        this.players = new ArrayList<Player>();

        for(Player player: players){
            this.players.add(player);
        }

    }

    private void distributeCards(){
        ...

    }

    public void start(){
        distributeCards()
        ...

    }

}

the distributeCards method of Game class needs to modify the cards attribute of a Player object. If I declare a public or protected method in the Player class for that, other classes in the same package will have the privilege as well but I don't want that. In this situation what can I do?

Let me know if I'm breaking any rules of design principles or design patterns.

Aucun commentaire:

Enregistrer un commentaire