子类是否继承接口?

2022-01-24 00:00:00 polymorphism java

快速提问,我正在学习接口和继承.

Quick question, I'm learning about interfaces and inheritance.

这不是实际代码,只是一个示例.假设我有抽象类 Animal.像马和犬类这样的群体有一些遗传.还有一个界面宠物".它将用于 Animal 的不同子类.犬类Dog"的子类实现了Pets"接口.因此Dog"的所有子类也都实现了Pet"接口,而不必在Dog"的每个子类上单独实现Pets",对吧?

This is not actual code, just an example. Let's say I have the abstract class Animal. There's some inheritance with groups like horses, and canines. There's also an interface "Pets". It's gonna be used on different subclasses of Animal. The subclass of canine "Dog" implements the interface "Pets". Therefore all subclasses of "Dog" also implement the interface "Pet" without having to individually implement "Pets" on each subclass of "Dog", right?

推荐答案

如果你有:

abstract class StaffMember implements MyInterface

在哪里

interface MyInterface {
    void myMethod();
} 

然后所有扩展 StaffMember 的类都将继承 MyInterface 类型,并且您将能够在代码的其他部分中通过此基类型引用它们,其中 MyInterface 实例应作为操作数/参数,例如:

then all of the classes extending StaffMember will inherit the type MyInterface, and you will be able to refer to them by this base type in other parts of the code where a MyInterface instance is expected as an operand/argument, for example:

void otherMethod(MyInterface param) { //... }

接口 MyInterface 的实际实现可以在抽象类中进行,也可以在任何扩展抽象类的类中进行.重要的是,在这种情况下,myMethod() 是在继承层次结构中的某个位置指定的,以便 JVM 可以找到它的定义来调用.

The actual implementation of the interface MyInterface can take place either in the abstract class, or in any of the classes extending the abstract class. The important thing is simply, in this case, that myMethod() is specified somewhere in the inheritance hierarchy, so that the JVM can find a definition of it to invoke.

相关文章