it seems to provide an abstract method for the Shape class, where all subclasses have common behavior, is best suited for this task.
Consider this the Shape class:
public abstract class Shapes{ public abstract void Draw(); }
Rectangle class:
public class Rectangle extends Shapes{ public void Draw(){ System.out.println("Rectangle"); } }
Circle class:
public class Circle extends Shapes{ public void Draw(){ System.out.println("Circle"); } }
Considering that both Circle and Rectangle are of type Shape , you can create objects of type Circle or / and Rectangle , add them to ArrayList, iterate over it and call Draw() for each object:
ArrayList<Shapes> shapes = new ArrayList<>(); shapes.add(new Circle()); shapes.add(new Rectangle()); shapes.forEach(Shapes::Draw);
when the Draw() method is called for each object:
Circle Rectangle
source share