An advice for a design between parent and child classes?

Robot0110 :

I'm working on a physics simulation.

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

The parent class, of course, doesn't have a draw() method but each of the child classes does. Therefore, when I'm looping trough the list to draw each element, it doesn't allow me because there isn't a draw() method in the Shape class (as I'm defining the list as ArrayList<Shape>, and adding each new element with a child class instance).

Is there a way to resolve this problem in a good and neat way?

abhipil :

The neatest 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's children you can create an AbstractShape class implementing Shape with any additional code and extend the child classes using this abstract class.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=476884&siteId=1