Java why interface extends interface

Solution 1:

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.

Solution 2:

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.

Solution 3:

Yes, there is one big difference.

In your first example, your new interface B is defined to extend from A, so going forward, any class that implements B automatically implements A. Basically, you're telling the compiler "here's what it means to be an A, here's what it means to be a B, and oh, by the way, all B's are also A's!" That lets you say things like...

class C implements B {
    ... you implement all of the methods you need...
    ...blah...
    ...blah...
}
A myNewA = new C();

and that works fine.

But, in your second example, you don't declare B to extend A, so the code above wouldn't work. When you try to assign an instance of (the second kind of) C into a reference for A, it would complain, because you haven't told the complier that "all B's are really A's." (i.e. there is no relation between B and C)

Solution 4:

there is only one comment in

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

if you declare A a = new C();

you CANNOT call method2(); because interface A knows nothing about elements in interface B even you implements methods in class C