以下是我的原始问题的玩具问题。 Bird
是一个接口。 Cardinal
是Point
的子类,它实现Bird
接口。 Aviary
类执行实施。如何在子类的实例方法中返回超类对象?
问:我应该把什么在getPosition()
实例方法使得Aviary
类正确携带getPosition()
方法?
如果bird
接口中的抽象方法编码错误,请纠正我的错误。
public interface Bird{
public Point getPosition();
}
public class Point{
private int x;
private int y;
// Constructs a new Point at the given initial x/y position.
public Point(int x, int y){
this.x = x;
this.y = y;
}
// Returns the x-coordinate of this point
public int getX(){
return x;
}
// Returns the y-coordinate of this Point
public int getY(){
return y;
}
}
问题是,在下面的代码:
public class Cardinal extends Point implements Bird{
// Constructors
public Cardinal(int x , int y){
this(x,y);
}
// not sure how to write this instance method
public Point getPosition(){
???????????
}
}
public class Aviary{
public static void main(String[] args){
Bird bird1 = new Cardinal(3,8);
Point pos = bird1.getPosition();
System.out.println("X: " + pos.getX() + ", Y: " + pos.getY());
}
}
在getPosition()中,写下:return this – pd30 2014-09-25 04:13:54
为什么'Cardinal'是'Point'?不应该使用'Cardinal'实例来使用'Point'实例变量来跟踪它的位置吗?如果代码期望某个位置有鸟,那将是非常令人惊讶的。 – user2357112 2014-09-25 04:15:42
'Cardinal'是''Point''吗?这是要检查继承是否有意义的典型问题。另一方面,说“红衣主教的位置是一个点”是完全合理的。这意味着使用组合代替更合理。为此,只需在'Cardinal'类中添加一个'Point'成员变量即可。更好的做法是让'Bird'成为一个具有'Point'成员变量的抽象类,因为**每个**都有一个位置。 – 2014-09-25 04:16:59