Reputation:
I can't understand how multiple inheritance is achieved using iterfaces when we have to implement the abstract method ourselves?
Suppose I have
class A implements B,C{
public void B()
{//method of interface B implemented}
public void C()
{//method of interface C implemented}
}
We can just do this
class A{
public void B()
{//method of interface B implemented}
public void C()
{//method of interface C implemented}
}
I don't get how is it useful if we are not getting readymade methods, in what situations and how is this useful? Can someone please explain with an example? Thanks !!
Upvotes: 3
Views: 181
Reputation: 12440
The interfaces are used for subtyping, not implementation inheritance. It cannot be used for code reuse, only for creating type hierarchies / for polymorphism (well in fact it can be used for code reuse since Java 1.8, but I would consider that an expert feature to be used only if there's no other acceptable solution).
The implementation inheritance is one way to achieve code reuse - writing the code only once and using it in all subclasses. There are other ways to achieve that, see Prefer composition over inheritance for one such approach.
Subtyping / polymorphism is not about reusing the code, but about being able to work with different classes the same way.
For example, java.util.LinkedList
implements both java.util.List
(allowing it to be used as a list) and java.util.Deque
(allowing it to be used where you need a stack / queue).
Upvotes: 5
Reputation:
The multiple interfaces allow you to treat a given object as many different things, all with type safety.
How you actually achieve the correct behavior for each "facet" of the object is up to you.
C++ allows you to get help in achieving the behaior, but at the cost of far more complex object model.
Upvotes: 0
Reputation: 201447
Good news! In Java 8+, interfaces may have Default Methods; so you can provide an implementation in the interface.
interface B {
default void B() {
System.out.println("In the interface method");
}
}
Upvotes: 0