2015-11-30 125 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

相关问题