我有一个名为shape的接口,只用一个方法来计算形状的面积。然后我有两个类Shape和Rectangle来实现形状界面。所有的类都有相应的setter,getters和calcArea方法。主,我有一个ArrayList,将存储2个矩形和两个圆圈。我将如何将矩形和圆圈添加到数组中?我试图做shapeArr.
,我的方法从矩形和圆不出现。我的代码如下,任何帮助表示赞赏。谢谢!两个类的ArrayList
public interface Shape {
public double calcArea();
}
public class Circle implements Shape {
private int radius;
private double area;
public Circle() {
radius = 1;
}
public void setRadius(int r){
radius = r;
}
public int getRadius(){
return radius;
}
@Override
public double calcArea() {
area = (Math.PI * (Math.pow(radius, 2)));
return area;
}
}
public class Rectangle implements Shape{
private int height;
private int width;
public int area;
public Rectangle(){
height = 1;
width = 1;
}
public void setHeight(int h){
height = h;
}
public void setWidth(int w){
width = w;
}
public int getHeight(){
return height;
}
public int getWidth(){
return width;
}
@Override
public double calcArea() {
area = (height * width);
return area;
}
}
import java.util.ArrayList;
public class ShapeDemo {
public static void main(String[] args) {
ArrayList<Shape> shapeArr = new ArrayList<Shape>(4);
}
public static void displayArea(Shape s) {
System.out.println("The area of the shape is " + s.calcArea());
}
}
但问题是什么?在你的数组对象中只能使用'Shape'类型的方法。如果你想使用特定的子类方法,你需要将对象从对象转换为特定类型,但在这种情况下,你应该完全知道什么是对象类型。 – sphinks