Java 该字段不可见
所以我想创建一个“Ball”类来扩展一个“Thing”类。我为构造函数中共享的变量(例如x、y、sizeX)调用super命令。但是当我尝试使用它们时(特别是在跳转函数中),它会给我一个错误“meteringtomakeagame.Thing.x不可见” 请注意,我的项目名为“MeTryingToMakeAGame”Java 该字段不可见,java,Java,所以我想创建一个“Ball”类来扩展一个“Thing”类。我为构造函数中共享的变量(例如x、y、sizeX)调用super命令。但是当我尝试使用它们时(特别是在跳转函数中),它会给我一个错误“meteringtomakeagame.Thing.x不可见” 请注意,我的项目名为“MeTryingToMakeAGame” class Ball extends Thing { Ball(int x, int y, int sizeX, int sizeY, int speed, int jump
class Ball extends Thing {
Ball(int x, int y, int sizeX, int sizeY, int speed, int jumpheight) {
super(x,y,sizeX,sizeY);
}
void jump() {
x-=jumpHeight;
}
}
class Thing {
private int x;
private int y;
private int sizeX;
private int sizeY;
Thing (int x, int y, int sizeX, int sizeY) {
this.x = x;
this.y = y;
this.sizeX = sizeX;
this.sizeY = sizeY;
}
}
字段
x
是私有的,因此它仅在类Thing
中可见。
要使子类的字段/方法可见,请使用修饰符
protected
,因为x是私有的,所以不能直接访问它。为了访问它,您可以为Thing类中的x字段创建一个getter方法,它们是私有的,所以实现getter方法。