访问超类字段

Ome*_*mer -1 java inheritance

例如,我有抽象类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();

}
Run Code Online (Sandbox Code Playgroud)

现在我的课程Rect扩展自Shape:

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

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

Phi*_*der 6

只需为他们制作一些吸气剂:

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

或使属性受到保护.

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


exc*_*on1 5

只要它们存在,你就无法得到它们private.protected反而让他们.

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