Frage

The title is quite self-explanatory: if I have a class which implements some interface, is that interface automatically implemented in an inherited class?

Note: This question has been asked before, but concerning Visual Basic. I apologize if it's a duplicate, but I simply couldn't find the answer anywhere.

War es hilfreich?

Lösung

Yes, in Java at least, interface implementation propagates from superclass to subclass.

In a general sense, both class inheritance and interface implementation represent an "is-a" relationship:

interface Vehicle { /* ... */ }
class Car implements Vehicle { /* ... */ }
class ElectricCar extends Car { /* ... */ }

// This works because ElectricCar is a Car, which is a Vehicle.
Vehicle vehicle = new ElectricCar();

In practice, methods that are part of an interface implementation are required to be public, so any instantiable implementor of an interface (e.g. ElectricCar above) will have exposed all of the methods required by the interface, either by inheritance from its superclass or by its own necessarily-public overrides.

Note that nothing is "automatically implemented": If Car were marked abstract it could be missing implementations for one or more of Vehicle's methods, as if Car had itself marked the unimplemented Vehicle method as abstract. Under any circumstance, the subclass ElectricCar would be considered (and required to be) an implementor of Vehicle, but consequently if Car doesn't provide an implementation of a Vehicle method then ElectricCar will not compile until it provides its own.

Andere Tipps

Everything that's not marked private is inherited by child classes, so yes, class members implemented for an interface will be inherited. Since interface members cannot be private (for obvious reasons), everything that the base class implements will have to be inherited by the child class.

An interface is just a contract, saying "this type will implement these members with the same signatures".

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top