D
D
dc65k2020-09-04 16:44:57
Java
dc65k, 2020-09-04 16:44:57

How to correctly call a method on an object stored in an ArrayList?

Hello. At the stage of learning Java, experimenting with collections, I encountered a moment, I would be grateful if you could tell me how to correctly implement the idea below.
There is an abstract class Shape:

public abstract class Shape {
    public abstract double area();
}


Next is the Circle shape class:
public class Circle extends Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double getRadius() {
        return radius;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.pow(this.radius, 2) * Math.PI;
    }

    @Override
    public String toString() {
        return "Circle{" +
                "radius=" + radius +
                '}';
    }

}


Next is the Rectangle shape class:
public class Rectangle extends Shape {

    private double width;
    private double height;

    public Rectangle(double width, double height) {
        this.width = width;
        this.height = height;
    }

    public double getWidth() {
        return width;
    }

    public void setWidth(double width) {
        this.width = width;
    }

    public double getHeight() {
        return height;
    }

    @Override
    public double area() {
        return this.width * this.height;
    }

    @Override
    public String toString() {
        return "Rectangle{" +
                "width=" + width +
                ", height=" + height +
                '}';
    }

}


And, directly, the Main class
public class Main {

    public static void main(String[] args) {
        ArrayList<Shape> shapesList = new ArrayList<>();

        Circle circle = new Circle(10);
        Rectangle rectangle = new Rectangle(20, 20);

        shapesList.add(circle);
        shapesList.add(rectangle);
        System.out.println(shapesList);

        for (Object shape: shapesList) {
            System.out.println(shape.toString());

            shape.area(); // ????
        }
    }
}


I assumed, obviously erroneously, that the methods of each object are also stored in the ArrayList. And in the loop I wanted to call the area () method, which every object has.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
illuzor, 2020-09-04
@dc65k

In the loop Object. It definitely doesn't have an area() method. You need to replace Object with Shape.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question