如果这句话措辞不佳或可搜索,我很抱歉,我在上面找不到任何东西,而且我几乎完全是自学成才。
我有一个Entity
类和多个子类,Building
并且Creature
在这里是相关的。
我有一个setTarget(Entity e)
我想同时用于Building
和Creature
类的方法,因为在此级别上它们是相同的。
我想知道是否可以将e强制转换为aBuilding
或a,Creature
取决于它是哪种类型,而不是用相同的代码创建2个整个方法。
private void setTarget(Entity e) {
if (e.getType.equals("Creature")) {
Creature c = (Creature)e; //rest of code assumes c is now a creature rather than a building
}
}
我意识到我可以通过将目标机制放到Entity
类中来做到这一点,但是那段代码将与所有其他没有/需要目标的子类无关。
任何帮助或提示将不胜感激,在此先感谢。
编辑:我调查了instanceof,它肯定清理了一下代码,但没有人理解我的意思;
private void setTarget(Entity e) {
if (e instanceof Creature) {
Creature c = (Creature)e;
} else if (e instanceof Building) {
Building c = (Building)e;
}
//Building OR Creature code here ie;
c.setTarget();
}
这是可以实现的吗?
您可以使用Java关键字instanceof
或getClass()
。两者之间的区别在于,如果说一个类是SmallBuilding
subclasses Building
,mySmallBuilding instanceof Building
则将返回true,而mySmallBuilding.getClass().equals
(Building.class)
将返回false,因为调用getClass()
aSmallBuilding
将返回Class
与aBuilding
类不同的对象。话虽如此,通常建议instanceof
在像您这样的依赖于子类的程序中使用,以及getClass()
例如在编写equals()
方法时使用(因为两个对象必须属于同一类)。这是一个如何工作的示例:
private void setTarget(Entity e) {
if (e instanceof Creature) {
Creature c = (Creature)e;
// Creature-specific code here
} else if (e instanceof Building) {
Building b = (Building)e;
// Building-specific code here
}
// Could add an else for other Entity subclasses (might throw UnsupportedOperationException)
}
编辑:根据您对问题所做的编辑,您可以执行以下操作:
private void setTarget(Entity e) {
if (e instanceof Creature) {
Creature c = (Creature)e;
c.setTarget();
} else if (e instanceof Building) {
Building b = (Building)e;
b.setTarget();
}
// Could add an else for other Entity subclasses (might throw UnsupportedOperationException)
}
您确实必须setTarget()
在两个if
语句中都包含。另一个选择是为定义一个接口setTarget()
,如下所示:
public interface Targetable {
public void setTarget();
}
然后有Building
和Creature
隐含Targetable
。然后,您可以定义setTarget()
为:
private void setTarget(Targetable t) {
t.setTarget();
}
或者:
private void setTarget(Entity e) {
if (t instanceof Targetable) {
((Targetable)t).setTarget();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句