假设我有这个
interface Movable {//some stuff}@H_403_3@我有
class Car implements Movable {//some stuff}@H_403_3@也许我有
class Bike implements Movable {//some stuff}@H_403_3@我注意到如果我有这个:
ArrayList<Movable> movableThings = new ArrayList<Movable>(); movableThings.add(some kind of Car) movableThings.add(some kind of Bike) movableThings.add(some kind of Bike)@H_403_3@这可以称为:
for(Movable m: movableThings)@H_403_3@但如果我这称呼我,我会得到不兼容的类型:
for(Bike b: movableThings)@H_403_3@有人可以解释,也许可以提供更好的方法吗?
我知道我可以使用foreach Movable m:movableThings然后使用instanceof来检查自行车但是还有另外一种方法吗?编辑:好的,谢谢你们澄清……所以我想我要么使用instanceof,要么重新设计我的游戏
解决方法
我不建议使用instanceof.实现公共接口的两种类型的要点是,在使用接口时,消费者代码不应该关注具体的实现.当我在equals()之外看到instanceof时,我往往会非常怀疑.
如果您想要来自不同实现的不同行为,请使用多态分派而不是instanceof:
interface Movable { void move(); } class Bike implements Movable { public void move() { // bike-specific implementation of how to move } } class Car implements Movable { public void move() { // car-specific implementation of how to move } }@H_403_3@for (Movable m : movableThings) { m.move(); }@H_403_3@如果您只想迭代自行车类型,请创建仅包含自行车的集合:
List<Bike> bikes = new ArrayList<Bike>(); // etc... for (Bike bike : bikes) { // do stuff with bikes }@H_403_3@注:您几乎应该始终将集合声明为List(接口)而不是ArrayList(接口的实现).
也可以看看
> Avoiding instanceof in Java
> Avoiding instanceof when checking a message type
> How does one use polymorphism instead of instanceof? (And why?)
> Avoiding ‘instanceof’ in Java
> when should we use instanceof and when not如果您还没有,您可能还想阅读The Java Tutorials: Interfaces and Inheritance.