访问超类字段



例如,我有抽象类Shape,它获取形状的坐标:

public abstract class Shape{
    private int x;
    private int y;
    public Shape(int x, int y){
        this.x=x;
        this.y=y
    }
    public abstract void onDraw();
}

现在我有类RectShape扩展:

public class Rect extends Shape{
    private int height;
    private int width;
    public Rect(int height, int width){
        this.height=height;
        this.width=width;
    }
    @Override
    public void onDraw(){
        //this method should get the width and height and the coordinates x and y, and will print the shape rect
    }
}

现在我的问题是:如何从Rect中获取抽象类Shape的坐标x和y?

只要它们private,你就无法获得它们

。 改为将它们protected

更多信息可以在这里找到。

简单地为他们做一些getter:

public abstract class shape{
    private int x;
    private int y;
    public shape(int x,int y){
        this.x=x;
        this.y=y
    }
    public abstract void onDraw();
    }
    public int getX() {
        return this. x;
    }
    public int getY() {
        return this. y;
    }

或使属性受到保护。

请注意,如果创建rect,则永远不会设置 x 和 y,因为您没有调用超构造函数

你不能。它是私有的全部意义在于您无法获取变量。如果全班没有给出任何找出它的方法,你就无法得到它。

最新更新