gpt4 book ai didi

java - 抽象类的私有(private)字段不能在子类中访问

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:54:08 27 4
gpt4 key购买 nike

我的类代表我的简单游戏中的每个对象(玩家、敌人、光束等——它们都有许多共同点,如速度、位置、伤害)。所以我创建了名为 Thing 的类。这是它的样子:

public abstract class Thing {
private Image image;
private float x;
private float y;
private float speed;
private final int WIDTH;
private final int HEIGHT;

public Thing(String filename, float x, float y, float speed) {
try {
Image image = ImageIO.read(new File(filename));
} catch (Exception e) {}
this.x = x;
this.y = y;
this.speed = speed;
WIDTH = image.getWidth(null);
HEIGHT = image.getHeight(null);
}

//Zwraca ksztalt do sprawdzania czy contains...
public Rectangle2D getShade() {
return new Rectangle2D.Float(x, y, WIDTH, HEIGHT);
}

public Image getImage() {
return image;
}

public Point2D getPoint() {
return new Point2D.Float(x, y);
}

public float getX() {
return x;
}

public float getY() {
return y;
}
}

我扩展了 Player 类:

public class Player extends Thing {
public Player(String filename, float x, float y, float speed) {
super(filename, x, y, speed);
}

public void moveToPoint(Point2D targetPoint) {
int targetX = (int)targetPoint.getX();
int targetY = (int)targetPoint.getY();
if ( ((int)x+20 < targetX+3) && ((int)x+20 > targetX-3) ) {
return;
}
float distanceX = targetX - x;
float distanceY = targetY - y;
//Dodanie 20px wymiarow statku
distanceX -= 20;
distanceY -= 20;
//Ustalenie wartosci shiftow
float shiftX = speed;
float shiftY = speed;
if (abs(distanceX) > abs(distanceY)) {
shiftY = abs(distanceY) / abs(distanceX) * speed;
}
if (abs(distanceY) > abs(distanceX)) {
shiftX = abs(distanceX) / abs(distanceY) * speed;
}
//Zmiana kierunku shifta w zaleznosci od polozenia
if (distanceX < 0) {
shiftX = -shiftX;
}
if (distanceY < 0) {
shiftY = -shiftY;
}
//Jezeli statek mialby wyjsc poza granice to przerywamy
if ( (((int)x+shiftX < 0) || ((int)x+shiftX > 260)) || ((y+shiftY < 0) || (y+shiftY > 360)) ) {
return;
}
//Zmiana pozycji gracza
x += shiftX;
y += shiftY;
}
}

这就是问题所在,因为我的 IDE 在 x、y 和速度字段下划了红色下划线,并告诉它们不能从 Player 类访问。我试图将它们更改为私有(private)和默认,但之后出现错误。我究竟做错了什么?当我从扩展 Thing 的类创建新对象时,我想复制所有字段并按照构造函数中的说明初始化它们。那么如何修复呢?

最佳答案

需要使用getX(), getY()等,因为x,y, speedThing 类的 private 变量。

Player extends Thing 的事实并不意味着 Player 可以访问 private 字段。 Thing 提供了 public get...set... 来访问它的 private 变量。

关于java - 抽象类的私有(private)字段不能在子类中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14165066/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com