gpt4 book ai didi

java - Foreach 通过不同的对象但都实现相同的接口(interface)可能吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:51:40 26 4
gpt4 key购买 nike

假设我有这个

interface Movable
{//some stuff}

我有

class Car implements Movable
{//some stuff}

也许我还有

class Bike implements Movable
{//some stuff}

我注意到如果我有这个:

ArrayList<Movable> movableThings = new ArrayList<Movable>();
movableThings.add(some kind of Car)
movableThings.add(some kind of Bike)
movableThings.add(some kind of Bike)

这可以称为:

for(Movable m: movableThings)

但如果我调用它,我会得到不兼容的类型:

for(Bike b: movableThings)

有人可以解释一下,并提供更好的方法吗?我知道我可以使用 foreach Movable m: movableThings 然后使用 instanceof 来检查 Bikes 但还有其他方法吗?

编辑: 好的,谢谢大家的澄清...所以我想我要么使用 instanceof,要么重新设计我的游戏

最佳答案

我不推荐使用 instanceof。实现公共(public)接口(interface)的两种类型的全部要点是,在使用接口(interface)时,消费者代码不应该关心具体的实现。当我在 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
}
}

将在每种类型上调用特定于实现的方法:

for (Movable m : movableThings)
{
m.move();
}

如果您只想遍历 Bike 类型,请创建一个仅包含 Bike 的集合:

List<Bike> bikes = new ArrayList<Bike>();
// etc...

for (Bike bike : bikes)
{
// do stuff with bikes
}

N.B. 您几乎应该始终将集合声明为 List(接口(interface))而不是 ArrayList(接口(interface)的实现) .

另见

如果您还没有,您可能还想阅读 The Java Tutorials: Interfaces and Inheritance .

关于java - Foreach 通过不同的对象但都实现相同的接口(interface)可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6296446/

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