0

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.

7
  • You need to actually declare them as abstract in the base class. Commented May 3, 2019 at 18:58
  • I do have the abstract classes declared in Shape (with no implementation of course) Commented May 3, 2019 at 19:00
  • 2
    post the classes Commented May 3, 2019 at 19:00
  • 2
    What is the exact error? Commented May 3, 2019 at 19:01
  • 1
    and notice you're missing get on the list: al.get(i).calculateArea() instead of al.calculateArea() Commented May 3, 2019 at 19:01

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.