我收到一条错误消息,指出“找不到方法 - getCenter”,但是每当我将“objects.get(i)”替换为像 a、b 或 d 这样的单个对象时,它都能找到该方法。我不明白为什么它无法从 ArrayList 中找到方法。
public class TestPoly
{
public static void main (String []args)
{
ArrayList objects = new ArrayList();
Circle2 a = new Circle2(33,10,4);
Cylinder2 b = new Cylinder2(21,15,40,5);
Oval2 c = new Oval2(3,7,34,10);
OvalCylinder2 d = new OvalCylinder2(5,11,5,5,7);
objects.add(a);
objects.add(b);
objects.add(c);
objects.add(d);
for (int i = 0; i < objects.size(); i++)
{
System.out.println("For " + objects.get(i).getClass().getName() + objects.get(i).getCenter());
}
}
}
Circle2就是这个。
public class Circle2
{
// instance variables
private int x;
private int y;
private int radius;
/**
* Constructor for objects of class circle
*/
public Circle2(int p_x, int p_y, int r)
{
// initialise instance variables
x = p_x;
y = p_y;
radius = r;
}
public int getRadius()
{
return radius;
}
public String getCenter()
{
return " the center is at (" + x + "," + y + ")";
}
}
Cylinder2、Oval2 和 OvalCylinder2 都只是 Circle2 的子类。