Search code examples
javainheritanceclass-design

Inheritence Class Design (in Java)


for a small game I want to design two classes which should draw my Units. I have the classes Unit and Settler which extends Unit.

To draw them I have the classes UnitView and SettlerView.

Now UnitView has a method public void draw(Graphics g) and SettlerView should use the same method. The difference in the two classes should be in the way they are getting the information to draw the Unit. Let's say Units are allways blue and Settlers have a Color depending on their health (which would be a field in Settler, where SettlerView has access to).

What would be a proper way to implement that? I want a clean design without public methods like setColor.

edit: This was my first approach:

public class UnitView {
    private Unit unit;
    public Color color; // I don't want to make it public. Setting it private + getter/setter does not seem to be different to me.
    private color calculateColor() { ...uses the information of unit... }
    public void draw(Graphics g) { ...something using the Color... }

}

public class SettlerView extends UnitView {
    private Settler settler;

    private color calculateColor() { ...this method overides the one of UnitView.... }
}

I want to use Polymorphism to call UnitView.draw. The key thing is the public field Color.


Solution

  • you can always override the parent draw method.

    so for example if parent method is

    public void draw(Graphic g){
         g.setColor(blue);
    }
    

    the child class will have

    @Override
    public void draw(Graphic g){        
        if  (this.health > 50){
            g.setColor(green);
        }else{
            g.setColor(red);
        }
        super.draw(g); // if you want to call the parent draw and just change color
    }