3

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 !!

3 Answers 3

5

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).

Sign up to request clarification or add additional context in comments.

2 Comments

It cannot be used for code reuse, only for creating type hierarchies, I do not understand what that means? By the way your answer is definitely helpful.
@spectre edited the answer, tried to clarify. Please ask if you need to clarify further, but read the linked wiki pages first please if you haven't already.
0

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");
    }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.