子类中无法访问抽象类的私有字段

Mic*_*bor 4 java

我有一个类,它代表我简单游戏中的每个对象(玩家,敌人,横梁等-它们都有很多共同点,例如速度,位置,dmg)。因此,我上了名为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我扩展了类播放器:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

kos*_*osa 5

你需要使用getX()getY()等等,因为xyspeedprivate对类变量Thing

Player extends Thing并不意味着Player可以访问private字段。Thing提供public get... set...用于访问其private变量。