加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Foreach通过不同的对象,但都可以实现相同的接口?

发布时间:2020-12-14 23:55:03 所属栏目:Java 来源:网络整理
导读:假设我有这个 interface Movable{//some stuff} 我有 class Car implements Movable{//some stuff} 也许我有 class Bike implements Movable{//some stuff} 我注意到如果我有这个: ArrayListMovable movableThings = new ArrayListMovable();movableThings.
假设我有这个
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来检查自行车但是还有另外一种方法吗?

编辑:好的,谢谢你们澄清……所以我想我要么使用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
    }
}

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

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

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

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

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

注:您几乎应该始终将集合声明为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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读