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

标签 java inheritance interface polymorphism

假设我有一个类扩展另一个类并实现一个或多个接口(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/

相关文章:

java - 编译器认为 Comparable 类型不是 Comparable

java - 将变量从 servlet 传递到 jsp 不起作用

C++——继承

c# - 声明成员时可以指定接口(interface)吗?

c# - 在 C# .NET 中实现接口(interface)

typescript - 接口(interface)在 Typescript 中有用吗(从架构上来说)?

java - spring security oauth2 (2.0.8) 使用 InMemory tokenstore 获取无效的访问 token

java - Spring Boot无法连接MySQL并在Docker/Docker compose中退出

java - 将对象声明为其父类(super class)与其类之间的区别?

asp.net - web.config 继承 : <clear/> causes XML Parsing Error in <system. webServer><modules>