Foreach通过不同的对象,但都可以实现相同的界面?

som*_*eur 6 java

假设我有这个

interface Movable
{//some stuff}
Run Code Online (Sandbox Code Playgroud)

我有

class Car implements Movable
{//some stuff}
Run Code Online (Sandbox Code Playgroud)

也许我有

class Bike implements Movable
{//some stuff}
Run Code Online (Sandbox Code Playgroud)

我注意到如果我有这个:

ArrayList<Movable> movableThings = new ArrayList<Movable>();
movableThings.add(some kind of Car)
movableThings.add(some kind of Bike)
movableThings.add(some kind of Bike)
Run Code Online (Sandbox Code Playgroud)

这可以称为:

for(Movable m: movableThings)
Run Code Online (Sandbox Code Playgroud)

但如果我这称呼我,我会得到不兼容的类型:

for(Bike b: movableThings)
Run Code Online (Sandbox Code Playgroud)

有人可以解释,也许可以提供更好的方法吗?我知道我可以使用foreach Movable m:movableThings然后使用instanceof来检查自行车但是还有另外一种方法吗?

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

Mat*_*all 9

我不建议使用instanceof.整实现一个共同的接口两种类型的是,使用接口时,消费者代码不应该关心的具体实施.当我看到instanceof外面时,我往往会非常怀疑equals().

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

for (Movable m : movableThings)
{
    m.move();
}
Run Code Online (Sandbox Code Playgroud)

如果您只想迭代Bike类型,请创建仅包含Bikes 的集合:

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

for (Bike bike : bikes)
{
    // do stuff with bikes
}
Run Code Online (Sandbox Code Playgroud)

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

也可以看看

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


Joh*_*zen 2

你确实需要使用instanceof. 您可能想编写一个过滤器函数以使其可重用。

话虽这么说,这可能是您希望使用继承来允许以相同的方式在两个类上调用相同的方法的情况。