Search code examples
javainterfacemultiple-inheritance

How interfaces in java used for code reuse?


I am learning java, and came to know that Java doesn't support multiple inheritance. So, java introduced interfaces for that. How does the problem of multiple inheritance is solved by interface?

What I read online : "Inheritance in java means code reuse".

If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B. How does it use the code re-usability feature?


Solution

  • You haven't given proper citations for any of the assertions that you make in your Question, so it is impossible to know what they are actually saying ... or why you think that they are say these incorrect or misleading things.


    I am learning java, and came to know that Java doesn't support multiple inheritance.

    That is correct.

    So, java introduced interfaces for that.

    That is INCORRECT. Java introduced interfaces to support polymorphism. Specifically polymorphism that does not depend on class inheritance.

    How does the problem of multiple inheritance is solved by interface?

    It isn't.

    Multiple inheritances are about inheritance of method and field declarations from multiple parent classes. Interfaces does not provide that, and it does not solve the problem.

    Interfaces do allow you to declare a common API (or APIS) and implement that API without necessarily sharing code. But with careful design you can do code-sharing under the hood any; e.g. by using the Delegation design pattern.

    What I read online : "Inheritance in java means code reuse".

    I doubt that what it actually said. Anyway, it is INCORRECT.

    Inheritance (of classes) is one way to achieve code reuse, but it is only one of many ways to achieve reuse. There are many others.

    If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B.

    I presume that you mean something like this:

    public interface I {
        void someMethod();
    }
    
    public class A implements I {
        void someMethod() {
             // some code
        }
    }
    
    public class B implements I {
        void someMethod() {
             // some code
        }
    }
    

    How does it use the code re-usability feature?

    There is no code reuse in that example. But this is not inheritance of classes (which I described as one way to achieve code reuse). It is a class implementing an interface.

    (Now in Java 8, you can put code into interfaces in certain circumstances; read up on the default methods feature. And that does allow direct code reuse via an interface. But I doubt that is what the sources you have been looking at are talking about.)