我试图通过此示例理解继承但不理解:我有一个简单的Point.java,Quadrilateral.java和Rectangle.java(Quadrilateral的子类)
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;
}
然后在子类矩形中,应从四边形继承矩形中的点。如果我想访问矩形类的点并且也许想知道Xposition,我应该怎么做?如果我写在矩形类中:点x = getP1()。getX(); (getX()在Point类中)不起作用,可能会编译idenftifier错误。但是即使我只写:Point x = getP1(); //从超类中也出现同样的错误。谢谢
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
如果不希望直接从派生类访问它们,则应该使用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());
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句