The following is a toy problem of my original problem. Bird is an interface. Cardinal is the subclass of Point and it implements the Bird interface. The Aviary class carries out the implementation.
Question: What should I put in the getPosition() instance method such that the Aviary class carries the getPosition() method correctly?
Please correct me if the abstract method in the bird interface is coded wrong.
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;
}
}
Question is in the following code:
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() );
}
}
CardinalaPoint? Shouldn't aCardinalinstance instead use aPointinstance variable to keep track of its location? It'd be pretty surprising if code expecting a location got a bird.CardinalaPoint? This is the typical question to ask to check if inheritance makes sense. On the other hand, it makes complete sense to say "A cardinal has a position which is a point." This implies that it makes more sense to use composition instead. To do this, simply add aPointmember variable to yourCardinalclass. Better yet, makeBirdan abstract class with aPointmember variable since every bird has a position.