Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An advice for a design between parent and child classes?

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?

like image 965
Robot0110 Avatar asked Apr 16 '17 02:04

Robot0110


2 Answers

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.

like image 143
abhipil Avatar answered Sep 28 '22 04:09

abhipil


it seems to provide an abstract method for the Shape class where all subclasses share a common behaviour is best for the task at hand.

Consider this is the Shape class:

public abstract class Shapes{
    public abstract void Draw();
}

the Rectangle class:

public class Rectangle extends Shapes{
    public void Draw(){
        System.out.println("Rectangle");
    }
}

the Circle class:

public class Circle extends Shapes{
    public void Draw(){
        System.out.println("Circle");
    }
}

now considering that both Circle and Rectangle are of type Shape, you can create objects of type Circle or/and Rectangle, add them to the ArrayList, iterate over it, and invoke the Draw() method on each object like so:

ArrayList<Shapes> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Rectangle());
shapes.forEach(Shapes::Draw);

result when Draw() method is invoked on each object:

Circle
Rectangle
like image 34
Ousmane D. Avatar answered Sep 28 '22 02:09

Ousmane D.