gpt4 book ai didi

java - Java中如何同时使用继承和接口(interface)的多态性?

转载 作者:行者123 更新时间:2023-11-30 02:22:18 35 4
gpt4 key购买 nike

假设我有一个类扩展另一个类并实现一个或多个接口(interface)。如何指定需要这种条件的类型?

例如:

class Eagle extends Animal implements Fly {
}

class Falcon extends Animal implements Fly {
}


public static void main (){
??? anAnimalWhoCanFly;
}

更新:我删除了该列表。假设我想要一个对象,它是扩展 Animal 并实现 Fly 的类的对象。

谢谢

最佳答案

如果您想要一种方法来指定,例如“扩展 Animal 并实现 Fly 的类型”,只需定义一个完全执行此操作的类即可:

public abstract class FlyingAnimal extends Animal implements Fly{ }

现在您已经有了从 FlyingAnimal 扩展的 EagleFalcon,而不是直接从 Animal 扩展而来:

public class Falcon extends FlyingAnimal {
public void fly(){ System.out.println("I'm a fast flier");
}

public class Eagle extends FlyingAnimal {
public void fly(){ System.out.println("I'm built for soaring");
}

public class Cat extends Animal {
// I'm a cat; I can't fly
}

现在你可以做这样的事情:

public void flyIt(FlyingAnimal fa){
fa.fly();
}

public void test(){
Falcon falcon = new Falcon();
Animal eagle = new Eagle();
Animal cat = new Cat();

flyIt(falcon); // OK: `Falcon` is a `Falcon`, which is also
// a `FlyingAnimal`
flyIt(cat); // COMPILE ERROR: `cat` is an `Animal`,
// which is not a subclass of `FlyingAnimal`
flyIt(eagle); // COMPILE ERROR: `eagle` is an `Animal`, which is
// not a `FlyingAnimal`
flyIt((Eagle)eagle);
// OK: because we know that `eagle` actually references
// an `Eagle`, we know the type-cast `(Eagle)eagle`
// will succeed at run-time; `Eagle` is a `FlyingAnimal`
// and thus is acceptable as an argument to `flyIt`
flytIt((FlyingAnimal)eagle);
// OK: because we know that `eagle` actually references
// an `Eagle`, which in turn is a `FlyingAnimal`, we
// know the type-cast `(FlyingAnimal)eagle` will
// succeed at run-time
flyIt((FlyingAnimal)cat);
// RUN-TIME ERROR: `cat` references a `Cat`, which is
// an `Animal` but not a `FlyingAnimal`, and so will
// not successfully convert to a `FlyingAnimal` at
// run-time.

关于java - Java中如何同时使用继承和接口(interface)的多态性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46459454/

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