Search code examples
javaoopinheritancevisibilitygetter-setter

Visibility of class variables in parent class


I have a class Player.java which extends Entity.java. In entity I define the x and y coordinates. In Game.java I create a player object: Player player = new Player(0, 0);. What should the visibility of the x and y variables in Entity.java be? I do not want to be able to set them directly in Game.java, but if I make them private I cannot access them from the child class Player.java. Should I just make the getters and setters in Entity.java and when I need x and y in the Player.java class call those methods? That would mean that every time I need x and y in Player.java to calculate something I would need to call the getter and setter.

Main.java

Player player = new Player(0,0);

Player.java

public Player(int x, int y) {
    super(x, y);
}

Entity.java

private/public int x;
private/public int y;

public Entity(int x, int y) {
    this.x = x;
    this.y = y;
}

Solution

  • If you want responsibility in your Entity class, make the properties private. Make protected getters and setters. This way Player can access the x and y properties indirectly and Game class can't set access these properties, because of the protected getters and setters.