2014-02-25 36 views
-1

比如我有抽象類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(); 

} 

現在我有類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 
    } 
} 

現在我的問題是:我如何從Rect內獲得抽象類Shape的座標x和y?

+1

請遵循命名約定 –

回答

5

只要他們是private,就不能得到它們。請改爲protected

的更多信息,可以發現here.

+1

也爲類矩形的構造應稱爲矩形()Y將永遠不會被設置,不是形狀()。 – jgitter

+0

或者爲它們設置getter方法... –

+0

在抽象類中設置getter/setter將使變量在每個其他子類中都可訪問,這是他可能不需要的。他只需要在'onDraw()'中使用'x'和'y',然後不需要使用getter。 – exception1

0

你不能。它的整個點是私人是你不能在變量。如果班級沒有給出任何解決辦法,你就無法得到它。

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; 
    } 

或使受保護的屬性。

注意的是X,如果你創建一個rect,因爲你沒有調用超級構造

+1

最初的例子不會編譯... –