2014-09-25 162 views
0

以下是我的原始问题的玩具问题。 Bird是一个接口。 CardinalPoint的子类,它实现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()); 
     } 
} 
+0

在getPosition()中,写下:return this – pd30 2014-09-25 04:13:54

+1

为什么'Cardinal'是'Point'?不应该使用'Cardinal'实例来使用'Point'实例变量来跟踪它的位置吗?如果代码期望某个位置有鸟,那将是非常令人惊讶的。 – user2357112 2014-09-25 04:15:42

+1

'Cardinal'是''Point''吗?这是要检查继承是否有意义的典型问题。另一方面,说“红衣主教的位置是一个点”是完全合理的。这意味着使用组合代替更合理。为此,只需在'Cardinal'类中添加一个'Point'成员变量即可。更好的做法是让'Bird'成为一个具有'Point'成员变量的抽象类,因为**每个**都有一个位置。 – 2014-09-25 04:16:59

回答

3

只返回对象本身:我给了一个答案

public Point getPosition(){ 
    return this; // returns a Point object 
} 

,但我不知道你是否有一个设计噩梦或独一无二的设计简化。一个执行Bird的子类让我把我的头撞在墙上,但在一个对象中使用这两种类型将会使得计算非常整洁(如果你有大量计算,那就是)。因为不是bird.getPosition().getX(),你可以写bird.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()); 
+0

谢谢。这使得现在更有意义。你让我意识到我不应该盲目地继承。 – mynameisJEFF 2014-09-25 04:37:23

2

Cardinal类对象有一个是,一个与Point类对象关系,所以你可以只return this;作为Krumia建议。

P.S.当引用子类中的超类来访问它的保护public方法时,可以使用super关键字。

相关问题