如何从ArrayList遍历对象调用抽象方法?

时间:2019-05-03 18:55:43

标签: java

我正在尝试使用循环遍历对象的Arraylist,但是当我调用要打印的抽象方法时,出现找不到符号的错误,例如:

ArrayList<Shape> al = new ArrayList<Shape>();
    Shape triangle = new Triangle(3.0, 2.5, 2.0);
    Shape rectangle = new Rectangle(2.0, 4.0);
    Shape circle = new Circle(1.0);
    al.add(triangle);
    al.add(rectangle);
    al.add(circle);
    for(int i = 0; i < al.size(); i++)
    {
        System.out.println(al.get(i), al.calculateArea(), al.calculatePerimeter(), al.toString());
    }
 }

全矩形类

public class Rectangle extends Shape
{

    private double length, width;

    public Rectangle(double length, double width)
    {
        double length1 = length;
        double width1 = width;
    }

    public double calculateArea()
    {
       double rectangleArea = length * width;
       return rectangleArea;
    }

    public double calculatePerimeter()
    {
        double rectanglePerimeter = (length * 2) + (width * 2);
        return rectanglePerimeter;
    }

    public String toString()
    {
        // put your code here
        return super.toString() + "[length=" + length + "width=" + width + "]";
    }

toString()和get(i)似乎可以正常工作,但是在调用以三角形,圆形等子类实现的抽象方法时,会出现符号错误。我尝试在子类中覆盖这些方法,但出现相同的错误。

1 个答案:

答案 0 :(得分:4)

这里:

al.calculateArea()

您在 list al而不是List元素上调用方法!

当然,列表本身对列表元素提供的方法一无所知!因为列表对象的类型为List(分别为ArrayList)。列表不是不是形状,因此您不能在列表上调用Shape方法。

您需要

 al.get(i).calculateArea()

例如!或更简单:

for (Shape aShape : al) {
  shape.calculateArea();...

换句话说:您不使用钱包付款 ,而是通过从钱包中取出钱来付款,然后再用这笔钱付款!