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 ?
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.
Yes, we can do it. An interface can extend multiple interfaces in Java.
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.
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.
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.
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