Answer the question
In order to leave comments, you need to log in
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();
}
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 +
'}';
}
}
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 +
'}';
}
}
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(); // ????
}
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question