下面是我原来问题的一个玩具问题。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() );
}
}
只返回对象本身:
public Point getPosition(){
return this; // returns a Point object
}
我给出了一个答案,但我不确定你是否有设计噩梦或独一无二的设计简化。实现Bird
的Point
子类会让我大吃一惊,但在一个对象中同时使用这两种类型会使计算非常简洁(如果你有大量计算的话)。因为您可以编写bird.getX()
,而不是bird.getPosition().getX()
。
Point bird1 = new Cardinal(3, 8);
Point bird2 = new Cardinal(4, 12);
// calculate the distance between two birds
double distance = Math.sqrt(Math.pow(bird2.getX() - bird1.getX(), 2) + Math.pow(bird2.getY() - bird2.getY(), 2));
但是,如果您的系统不是一个需要对仅由Point
对象表示的鸟类进行大量计算的鸟类模拟器,我认为您应该使用组合而不是继承。
public interface IBird {
public Point getPosition()
}
class Bird implements IBird {
private Point position;
public Bird(int x, int y) {
this.position = new Point(x, y);
}
public Point getPosition() {
return this.position;
}
}
// and then in main()
Bird bird = new Bird(3, 8);
Point pos = bird.getPosition();
System.out.println("X: " + pos.getX() + ", Y: " + pos.getY() );
Cardinal
类对象与Point
类对象具有is-a关系,因此您可以按照Krumia的建议仅使用return this;
。
请注意,当引用子类中的超类时,可以使用super
关键字来访问其受保护的和公共方法。