class 变量在父 class 中的可见性

Visibility of class variables in parent class

我有一个扩展 Entity.java 的 class Player.java。在实体中,我定义了 x 和 y 坐标。在 Game.java 中,我创建了一个播放器对象:Player player = new Player(0, 0);。 Entity.java 中 x 和 y 变量的可见性应该是多少?我不想直接在 Game.java 中设置它们,但如果我将它们设为私有,我就无法从子 class Player.java 访问它们。我是否应该只在 Entity.java 中创建 getters 和 setters 并且当我在 Player.java class 中需要 x 和 y 时调用这些方法?这意味着每次我需要 Player.java 中的 x 和 y 来计算一些东西时,我需要调用 getter 和 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;
}

如果您想在 Entity class 中承担责任,请将属性设为私有。创建 protected 个 getter 和 setter。这样 Player 可以间接访问 x 和 y 属性,而 Game class 不能设置访问这些属性,因为 protected getter 和 setter。

您可以同时设置protected,只使用子class的super.x ; super.y ;访问。 最好不要使用 setter 和 getter(对象编程)