2015-11-30 132 views
1

IM試圖理解這個例子繼承,但不明白:我有一個簡單Point.java,Quadrilateral.java和Rectangle.java(四邊形的子類)如何在實例形成另一個類時訪問超類的實例?

public class Quadrilateral{ 

private Point p1; 
private Point p2; 
private Point p3; 
private Point p4; 

public Quadrilateral(int x1, int y1,int x2, int y2, int x3,int y3, int x4, int y4){ 


    p1 = new Point(x1, y1); 
    p2 = new Point(x2, y2); 
    p3 = new Point(x3, y3); 
    p4 = new Point(x4, y4); 

} 

public Point getP1(){ 
    return p1; 
} 

public Point getP2(){ 
    return p2; 
} 

public Point getP3(){ 
    return p3; 
} 

public Point getP4(){ 
    return p4; 

}

然後在子類矩形,點應該從Quadrilateral的矩形繼承。如果我想訪問點矩形類的表格,也許知道Xposition,我應該怎麼做?如果我在矩形類中寫入:Point x = getP1()。getX(); (getX()在Point類中)它不起作用,編譯期望的錯誤標識符。但即使我寫的只是:點x = getP1(); //從該superclass.Same error.Thank你

public class Rectangle extends Quadrilateral{ 



    public Rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4,int y4){ 
     super(x1,y1, x2,y2, x3,y3, x4,y4); 

    } 

    //how to access here point1, piont2 form superclass? 
    //Point x = getP1(); doesn't work 
+2

'getP1()'是正確的''idenftifier expected''意思是你的java語法中的其他東西是錯誤的。你能舉一個不起作用的例子嗎? – zapl

+0

謝謝zapl是的你是正確的getP1()是正確的!我正在保存修改文件的副本沒有編譯,因此無法看到getP1()的正確工作... resutl謝謝! –

回答

0

你應該讓你的Point S的protected代替private,如果你想訪問它們直接來自派生類。否則,您可以簡單地使用您的getPX()間接訪問它們。

要在派生類中訪問它們,您需要使用一種方法。例如:

public class Rectangle extends Quadrilateral{ 
    public Rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4,int y4){ 
     super(x1,y1, x2,y2, x3,y3, x4,y4); 
    } 

    //just an example: 
    public Point getPoint1and2Sum() { 
     return getP1().translate((int) getP2().getX(), (int) getP2().getY()); 
    } 
} 

或者,如果你讓你的Point變量protected

public class Rectangle extends Quadrilateral{ 
    public Rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4,int y4){ 
     super(x1,y1, x2,y2, x3,y3, x4,y4); 
    } 

    //just an example: 
    public Point getPoint1and2Sum() { 
     return p1.translate((int) p2.getX(), (int) p2.getY()); 
    } 
} 
0

你應該看看不同類型的可見性。

  • private:只有類本身可以訪問私有成員
  • 默認的(無可見性描述符):在同一個包中的所有類都可以訪問成員
  • protected:所有類在同一個包和類擴展父類可以存取權限的保護成員
  • public:所有類都可以訪問公共成員

所以,如果你想直接訪問點p1 - p4,你將不得不申報protected

相關問題