Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to guarantee an interface extends a class in Java?

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() { ... } } 
like image 253
math4tots Avatar asked Jan 01 '13 09:01

math4tots


People also ask

Is it possible for an interface to extend a class?

An interface can extend other interfaces, just as a class subclass or extend another class.

Does interface extend object class by default?

Object is a class, and interfaces can not extend classes, so "no" - the interface doesn't inherit anything from any class.

Why an interface is not extended by a 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.


1 Answers

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.

like image 83
thkala Avatar answered Sep 18 '22 18:09

thkala