子类继承接口吗? [英] Do subclasses inherit interfaces?

查看:63
本文介绍了子类继承接口吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个简单的问题,我正在学习接口和继承.

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

这不是实际的代码,仅是示例.假设我有抽象类Animal. 马和犬类等群体有一定的继承权.还有一个宠物"界面.它将用于Animal的不同子类.犬狗"的子类实现接口宠物".因此,狗"的所有子类也都实现了宠物"接口,而不必在狗"的每个子类上单独实现宠物",对吧?

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.

这篇关于子类继承接口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆