如何创建一个实现了3个接口的此类(Array)的数组?

huangapple go评论69阅读模式
英文:

How to create an Array of this class that implements 3 interfaces?

问题

我正在练习多态、继承和接口,所以我决定创建一个名为“Duck”的类,这个类可以行走、游泳和飞行,同时我也创建了一个名为“Eagle”的类和一个名为“Flyer Fish”的类。

Duck实现了3个接口:Aquatic(水生)、Terrestrial(陆生)和Aerial(空中)
Eagle实现了2个接口:Aerial和Terrestrial
Flyer Fish实现了2个接口:Aerial和Aquatic(水生)

这些接口都继承自Animal,它只有一个方法:

public void eat();

然后我决定创建一个数组并触发它们各自的动作:

List<Animal> animals = new ArrayList<Animal>();
FlyerFish ff = new FlyerFish();
Eagle eg = new Eagle();
Duck dk = new Duck();
animals.add(ff);
animals.add(eg);
animals.add(dk);

for (Animal animal : animals) {
    if (animal instanceof Aquatic) {
        ((Aquatic) animal).swim();
    }
    if (animal instanceof Terrestrial) {
        ((Terrestrial) animal).walk();
    }
    if (animal instanceof Aerial) {
        ((Aerial) animal).fly();
    }
}

我感觉所有这些强制转换是不必要的,或者可以避免。

英文:

I am practicing polimorfism ,hierarchy and interfaces, so I decide to create a class "Duck", this class can Walk, Swim and Fly, also I have created a class eagle and flyer fish.

Duck Implements 3 Interfaces : Aquatic, Terrestrial and Aerial
Eagle Implements 2 Interfaces : Aerial and Terrestrial
Flyer Fish Implements 2 Interfaces : Aerialand Aquatic

Those interfaces extends from Animal that has only one method:

public void eat();

Then I decide to create an Array and trigger their respective actions:

List&lt;Animal&gt; animals = new ArrayList&lt;Animal&gt;();
FlyerFish ff = new FlyerFish();
Eagle eg = new Eagle();
Duck dk= new Duck();
animals.add(ff);
animals.add(eg);
animals.add(dk);

foreach(Animal animal : animals){
		if(animal instanceof Acuatico) {
			((Acuatico) animal).swim();
		}
		if(animal instanceof Terrestre) {
			((Terrestre) animal).walk();
		}
		if(animal instanceof Aereo) {
			((Aereo) animal).fly();
		}
}

I feel all those casts are unnecessary or can be avoided.

答案1

得分: 1

> 我觉得所有这些类型转换都是不必要的,或者可以避免。

事实并非如此。你所知道的关于 animal 的信息仅限于它是 Animal 类型,该类型具有 eat 方法。因此,你可以轻松地调用 animal.eat() 而无需进行类型转换。然而,并非所有的 Animal 都具有 swim() 方法,或者 walk() 方法,或者 fly() 方法。这就是为什么在调用那些方法之前必须对每种类型进行检查和类型转换的原因。

英文:

> I feel all those casts are unnecessary or can be avoided.

They are not. All you know about animal is that it is of type Animal, which has the eat method. Therefore you can easily call animal.eat() without casting. However, not all Animals have the swim() method, or walk(), or fly(). That is why you have to check for each type and cast before calling that method.

huangapple
  • 本文由 发表于 2020年9月25日 04:27:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/64053944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定