Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java why interface extends interface

I am wondering under what circumstances do we extend an interface from an interface? Because, for example

interface A{     public void method1(); } interface B extends A{     public void method2(); } class C implements B{     @Override public void method1(){}     @Override public void method2(){} } 

Isn't it equivalent to

interface A{     public void method1(); } interface B{     public void method2();      } class C implements A, B{     @Override public void method1(){}     @Override public void method2(){} } 

Are there any significant reasons behind ?

like image 439
peter Avatar asked Nov 18 '12 03:11

peter


People also ask

Should an interface extend another interface?

An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.

Can interface extends interface Java?

Yes, we can do it. An interface can extend multiple interfaces in Java.

Why should we not extend an interface?

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.


2 Answers

The significant reasons depend entirely on what the interface is supposed to do.

If you have an interface Vehicle and an interface Drivable it stands to reason that all vehicles are drivable. Without interface inheritance every different kind of car class is going to require

class ChevyVolt implements Vehicle, Drivable class FordEscort implements Vehicle, Drivable class ToyotaPrius implements Vehicle, Drivable 

and so on.

Like I said all vehicles are drivable so it's easier to just have:

class ChevyVolt implements Vehicle class FordEscort implements Vehicle class ToyotaPrius implements Vehicle 

With Vehicle as follows:

interface Vehicle extends Drivable 

And not have to think about it.

like image 142
Spencer Ruport Avatar answered Oct 20 '22 00:10

Spencer Ruport


Yes there is: it's like inheritance anywhere else. If B is a specialization of A then it should be written that way. The second one indicates that the class just happens to implement 2 interfaces with no relationship between them.

From the end result standpoint you could just use multiple interfaces in place of handling a hierarchy (just as you could avoid using inherited behavior in a class hierarchy). This would leave information more scattered, however, and as (if not more) significantly it obfuscates the intent of the software model.

like image 22
Matt Whipple Avatar answered Oct 19 '22 23:10

Matt Whipple