gpt4 book ai didi

java - 继承类设计(Java)

转载 作者:行者123 更新时间:2023-12-01 15:10:55 27 4
gpt4 key购买 nike

对于一个小游戏,我想设计两个应该绘制我的单位的类。我有类 UnitSettler ,它们扩展了 Unit

为了绘制它们,我有类 UnitViewSettlerView

现在UnitView有一个方法public void draw(Graphics g)并且SettlerView应该使用相同的方法。这两个类的区别应该在于他们获取绘制单元的信息的方式。假设 Units 始终为蓝色,而 Settler 的颜色取决于其健康状况(这将是 Settler 中的一个字段,其中 SettlerView 有权访问)。

实现这一点的正确方法是什么?我想要一个干净的设计,没有像 setColor 这样的公共(public)方法。

编辑:这是我的第一个方法:

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.... }
}

我想使用多态来调用UnitView.draw。关键是公共(public)字段Color。

最佳答案

了解多态性:

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

UnitView 和 SettlerView 应该从具有draw() 方法的基类派生。您可以将其抽象化,以便所有子类都必须实现它。

关于java - 继承类设计(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12380743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com