Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
munchschair Avatar asked Dec 12 '13 03:12

munchschair


People also ask

Do subclasses inherit everything?

What You Can Do in a Subclass. A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent.

Can a class inherit an interface Java?

Classes don't inherit from interfaces, they just implement them. You can extend (inherit from) a single class, but you can implement multiple interfaces.

Do subclasses inherit associations?

All statements that are made about a superclass also apply to all subclasses. We say that subclasses “inherit” attributes, associations, and operations from the superclass.

Do interfaces count as inheritance?

Implementing an interface is indeed inheritance, and inheriting one interface from another is inheritance.


1 Answers

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.

like image 119
csvan Avatar answered Oct 05 '22 23:10

csvan