This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I am confused with one issue in java. How interface can solve the problem of multiple class inheritance. Lets say I have three independent classes Calss1, Class2 and Class3. These three classes have three methods method1, method2 and method3 respectively. Now If I want to create a class called Class4 where I want to use method1, method2 and method3 of respective classes and overload them. As I cant use multiple inheritance then how interface can solves it ?
I am going to nitpick the wording of the question as well. If you want to overload the methods, this would mean you will use the name method name but have a different number of parameters or change the types, etc. Depending on what you are trying to solve, what would stop Class 4 from just coding the methods as you want them to be? Given that the method signature is different from what it is in Class1, 2, or 3 I am not sure what the end goal is intended to be.
If you meant "override" instead of overload, which would involve you writing your own implementation of the method then my suggestion would be to declare Interfaces1,2,3 with methods1,2,3 respectively and have Class4 implement all three interfaces. Any user of the methodN in context of the Interface definition could then be serviced by Class4 or ClassN.
Jayant Joshi wrote: As I cant use multiple inheritance then how interface can solves it ?
Because inheritance is primarily about type implementation and specialiaztion, NOT about code reuse. The only difference between MI of interface (what Java gives you) and MI of implementation (what you're referring to, and what most people refer to when they talk about Multiple Inheritance) is that Java's MI of interface does not give you code sharing. It does, however, give you the important part--the types.
Thanks everyone for your reply. Sorry Brian for not framing out question in a proper way but thanks to Jeff to do that. My doubt is very clear now. I too was thinking that may be interface is only for a particular context(Type) and Jeff made it very clear now. Because interface comes in the picture only during multiple inheritance and its issue of DDD, many people always see it with code reuse. It will be very good if they put it in a proper way during tutorials. Thanks again.