0

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.

4

2 に答える 2

1

ポリモーフィズムについて学ぶ:

http://en.wikipedia.org/wiki/Polymorphism_in_object-Oriented_programming

UnitViewとSettlerViewは、draw()メソッドを使用して基本クラスから派生する必要があります。すべてのサブクラスがそれを実装しなければならないように、それを抽象化することができます。

于 2012-09-12T03:27:57.297 に答える
0

親の draw メソッドはいつでもオーバーライドできます。

たとえば、親メソッドが

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

子クラスは

@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
}
于 2012-09-12T03:27:20.970 に答える