henry66912
henry66912

Reputation: 11

How to call abstract methods from an ArrayList traversing objects?

I am trying to use a loop to traverse an Arraylist of objects, but when I call abstract methods to be printed I get the symbol cannot be found error For example:

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());
    }
 }

Full rectangle class

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() and get(i) seem to work fine, but in calling the abstract methods implemented in triangle, circle etc subclasses the symbol error comes up. I tried overriding these methods in the subclasses but I get the same error.

Upvotes: 0

Views: 131

Answers (1)

GhostCat
GhostCat

Reputation: 140573

Here:

al.calculateArea()

You invoke the methods on your list al, not on a List element!

And of course, the List itself doesn't know anything about the methods your list elements provide! Because the list object is of type List (respectively ArrayList). A List is not a Shape, thus you can't call Shape methods on the list.

You need

 al.get(i).calculateArea()

for example! Or even simpler:

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

In other words: you don't pay with your wallet, you pay by fetching your money out of the wallet, and then you pay with that money!

Upvotes: 4

Related Questions