Suppose I have the following situation:
public abstract class Vehicle { public void turnOn() { ... } } public interface Flier { public void fly(); }
Is there a way that I can guarantee that any class that implements Flier
must also extend Vehicle
? I don't want to make Flier
an abstract class because I want to be able to mix a few other interfaces in a similar manner.
For instance:
// I also want to guarantee any class that implements Car must also implement Vehicle public interface Car { public void honk(); } // I want the compiler to either give me an error saying // MySpecialMachine must extend Vehicle, or implicitly make // it a subclass of Vehicle. Either way, I want it to be // impossible to implement Car or Flier without also being // a subclass of Vehicle. public class MySpecialMachine implements Car, Flier { public void honk() { ... } public void fly() { ... } }
An interface can extend other interfaces, just as a class subclass or extend another class.
Object is a class, and interfaces can not extend classes, so "no" - the interface doesn't inherit anything from any class.
A class can't extend an interface because inheriting from a class ( extends ), and implementing an interface ( implements ) are two different concepts. Hence, they use different keywords.
Java interfaces cannot extend classes, which makes sense since classes contain implementation details that cannot be specified within an interface..
The proper way to deal with this problem is to separate interface from implementation completely by turning Vehicle
into an interface as well. The Car
e.t.c. can extend the Vehicle
interface to force the programmer to implement the corresponding methods. If you want to share code among all Vehicle
instances, then you can use a (possibly abstract) class as a parent for any classes that need to implement that interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With