Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

java - Do subclasses inherit interfaces?

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you have:

abstract class StaffMember implements MyInterface

where

interface MyInterface {
    void myMethod();
} 

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) { //... }

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...