Design tip between parent and child classes?

I am working on a physical simulator.

I have an ArrayList that contains all the objects in my simulation. I have a parent class: Shape and two child classes: Circle and Rectangle .

The parent class, of course, does not have a draw() method, but each of the child classes. Therefore, when I iterate over the list to draw each element, this does not allow me because the Shape class does not have a draw() method (since I define the list as ArrayList<Shape> , and add each new element with an instance of the child class).

Is there a way to solve this problem in a nice and neat way?

+5
source share
3 answers

The easiest way to move forward is to use interfaces.

 public interface Shape { void draw(); } public class Rectangle implements Shape { @Override public void draw() { // draw rect } } public class Circle implements Shape { @Override public void draw() { // draw circle } } 

If you want Shape to share some other logic with it, you can create an AbstractShape class that implements Shape with any additional code, and extend child classes using this abstract class.

+4
source

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 
+4
source

This is how I do it.

A class called Shapes, which has a field for List < Shape. A form is an interface that contains the draw () method getArea () or any others. You have so many classes that implement Shape , circle, rectangle, square, etc.

0
source

Source: https://habr.com/ru/post/1266776/


All Articles