Java: Why multiple interfaces instead of multiple inheritance? [duplicate] - java

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why does Java allow multiple inheritance from interfaces but not from abstract/concrete classes
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed
Instead of inheriting from multiple classes (which Java doesn't allow), why are we told to implement multiple interfaces instead?
Surely the point of inheriting from multiple classes is the inherit their functionality - if you have to manually re-insert functionality (for each class extending a set of interfaces) what's the point of using the interfaces? There's no guarantee that two classes implementing the same set of interfaces will provide the same functionality - or am I missing something?

Multiple inheritance is something that can cause multiple problems.
Interfaces are used to give abilities to instances of the class that implement them. I personally use interfaces with composition(using instance variables that are references to other objects) in order to provide functionality to my class that would otherwise be achieved with multiple inheritance.
In other words my class provides the functionality promised by the interface implemented but internally my class instance uses the instance variable to do the job.
"There's no guarantee that two classes
implementing the same set of
interfaces will provide the same
functionality - or am I missing
something?"
About your statement above:
Each method should adhere to a contract so no matter how you implement it the functionality of the method should always be the same if this is what is supposed to do. If it breaks the contract it means it was implemented wrongly.

multiple inheritance may lead to cyclic inheritance.. to avoid that we are going for interface based inheritance..

You should read about the diamond dependency problem http://en.wikipedia.org/wiki/Diamond_problem and to avoid this Java chose interfaces over extension of multiple classes

Related

When to use interface vs abstract class after Java 8

I know this question has been asked many times and we have articles all over the internet but I still cannot fully understand, when should I use interface or abstract class since I am using Java 15.
Most of the articles talk about the differences and use cases before Java 8 which makes sense but not when you can basically provide body for your methods in interface.
The only thing that made sense to me is non-public and non-final restrictions.
I would really appreciate if somebody can point out 1-2 examples of the scenarios where I need to choose between interface and abstract class in Java 15. Also, would be great if it can be in terms of real life projects rather than Animal or shape class examples.
Thanks !!
default methods on interface
Apparently you are referring to the feature of “default methods” implementing behavior in an interface.
You should understand that the feature was added as a way around this dilemma: How to retroactively add features leveraging streams and lambda on existing interfaces without breaking existing classes that implement those interfaces?
Many new methods were added to those interfaces such as in the Java Collections Framework. Adding methods to an existing interface would automatically break all classes implementing the interface that are lacking the newly-required methods. Being able to provide a fallback, to give an implementation where one is now required but not yet existing, would resolve the dilemma. Thus « default methods » were born.
To quote from the Oracle tutorial linked above:
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
To quote this Answer by Brian Goetz, Java Language Architect at Oracle:
The proximate reason for adding default methods to interfaces was to support interface evolution
So this feature of adding default behavior to an interface was not meant to be a new mainstream feature in and of itself. The intent of default was not to replace abstract.
Indeed, some experienced Java experts have recommended against making a habit of writing default methods on an interface. They recommend pretty much ignoring that feature of the Java language. Continue to think of interfaces as simply defining a contract, and abstract classes as providing partial implementations meant to be completed in a subclass.
You are certainly free to write your own default methods on your interfaces. And certainly you should do so if you are in a similar situation of having published an interface that others may have implemented, and now you want to add methods. But unnecessarily adding default methods is likely to confuse other programmers who expect partial implementations on an abstract class rather than an interface.
Four situations calling for default method on an interface
In that same post linked above, Brian Goetz suggests three other cases beyond interface evolution where default methods on an interface may be appropriate. Here is a quick mention; see his post for details.
Optional methods - The default method throws an UnsupportedOperationException because we expect implementations of this interface to more often not want to implement this method.
Convenience methods
Combinators
Start with interface, move to abstract class for shared code
As for choosing between an interface and abstract class:
Generally start with an interface. Or several interfaces if you want various implementing classes to mix various contracts (see mixin).
Think twice before adding a default method. Consider if your situation meets one of the four cases recommended by Brian Goetz as discussed above.
If you come to realize that you have duplicated code across multiple classes, then consider centralizing that shared code to an abstract class to be used across subclasses.
Alternatively, use composition rather than inheritance (discussed below).
For example, you might have a class for domestic ShippingLabelUS as well as ShippingLabelCanada and ShippingLabelOverseas. All three need to convert between imperial pounds and metric kilograms. You find yourself copying that code between the classes. At this point you might consider having all three classes extend from abstract class ShippingLabel where a single copy of the weight conversion methods live.
While designing your API keep in mind that Java, like most OOP languages, has single-inheritance. So your subclasses are limited to extending only one class. To be a bit more specific about the single-versus-multiple inheritance, I will quote Brian Goetz from this PDF of a slide deck:
[regarding default methods on an interface]
Wait,is this multiple inheritance in Java?
• Java always had multiple inheritance of types
• This adds multiple inheritance of behavior
• But not of state, where most of the trouble comes from
Composition over inheritance
An alternative to using an abstract class for shared behavior is creating a separate class for specific behavior, then adding an object of that separate class to be kept as a member field on the larger class. Wise programmers often share this pearl of wisdom: Prefer composition over inheritance.
Regarding the shipping label example above, you could create a WeightConverter class, an object of which would be a member of each of the three label classes. In this arrangement, no need for the abstract class.

Java multiple inheritance particular issue

I have the following situation:
I need my class let's say A to extend JComponent and a different class let's say B.
Now, I know that multiple inheritance is not possible in java, and that a proper way to do this would be to implement BInterface which will give me access to all methods from B.
The issue is that class B contains ~15 methods, and inside A I only need to override 2 of them, and all the other ones to use the 'super' implementation.
Question is: is there a possible way to do this without having to implement inside A all the methods from B?
Note: I'm not trying to add too much complexity to my code, if the 'workaround' for this problem breaks oop programming principles then I should better redesign my code.
As you said multiple inheritance is not supported in java. But in general its a good practice to use composition instead of inheritance [Effective Java - item 18]. Read about it here
You can use default implementation of java 8 feature.
Create an interface named as ABinterface. provide all 13 methods as default means
having definition and declare 2 methods (like abstract methods).
Class A and B will implement ABinterface and override those 2 methods according to
their need.
Class A which will extend jsComponent and implement ABInterface can access all
other existing 13 methods also.
You haven't provided the enough information in this query. So you need to think according
to real word scenarios with oops concepts before implementing this.
You can also use composition instead of inheritance.

Java abstract class and interface [duplicate]

This question already has answers here:
Abstract class vs Interface in Java
(15 answers)
Closed 5 years ago.
In interview I have been asked following question. I tried to answer the question but I want exact answer of the question.
If I can simulate Abstract class as Interface, why java provided Interface?
This mean if in Abstract class I can mark all methods as abstract and then abstract class will work as interface, so why I need interface.
Can anyone explain me in brief.
That's a very standard interview question. The answer is: because you can implement multiple interfaces, but can't extend multiple abstract classes.
Example from the JRE: LinkedList is both a List and a Deque. These interfaces define the behaviour of the class. They do not provide any implementation details. While abstract classes could provide some.
Related questions: this and this. The latter is not directly related, but it shows why are interfaces needed, even in cases when an abstract class would suffice.
Interfaces define contracts & can define constants, but provide no implementation at all of the contracted methods.
Abstract classes can provide implementations of methods as well as member variables - if you want you can create an abstract class that defines everything except the fine-tuning you want in your concrete subclasses. You can't do this with interfaces, but you can implement multiple interfaces & extend only one parent class.
Both interfaces & abstract classes can be used to make use of concrete classes polymorphically.
Abstract classes do well to set default methods and set up the hierarchy. The issue is subclasses may only extend a superclass one-time. Interfaces on the other hand can extend each other multiple times and subclasses can implement any number of interfaces. This provides a lot of flexibility and affords the potential for change. Ideally, the can be combined i.e. abstract class implements interface1…interface2, best of both worlds.
The reason why interviewers ask this question is because your answer reflects your deep understanding of what a programming language (and a compiler) is. In particular, Java defines the concept of interface on top of (pure) abstract classes in order to (partially) support multiple inheritance (between interfaces). If this mechanism had not been introduced, we would have either no way of achieving some sort of multiple inheritance, or the big mess created by fully-fledged multiple inheritance in C++.
Answer
1) MULTIPLE INHERITANCE in java is achieved through interfaces.
2) If there is a situation where some explanation of a method is required, but not a full fledged one, the best way is to use abstract class.
3)Interfaces merely provide an AGREEMENT for the return type and the argument types.

Why did Java's designers choose interfaces and single inheritance? [duplicate]

This question already has answers here:
Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?
(21 answers)
Closed 9 years ago.
I can make abstract class equivalent to interface by putting all abstract methods within abstract class. Why did Java's designers choose to provide support for interfaces and single inheritance instead of multiple inheritance and abstract classes. What is the advantage?
At least for one reason (besides the conceptual differences between the two): you can implement multiple interfaces but you can only inherit from a single abstract class at most.
Class-based multiple inheritance is not supported by Java. You can only inherit from a single class, but you can implement multiple interfaces.
This becomes handy when you need to treat multiple classes polymorphicly when they have different inheritance trees.
An interface is a contract between a class and its behavior. If a class implements an interface, it MUST provide implementation for the methods specified in the interface. There's a number of things that differentiate the two, however.
Check out the Oracle website for more on the differences between interfaces and abstract classes:
http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
If you have multiple classes and you want to force that there would be some methods that should be common among them, irrespective of their behavior(implementation), Interface does that for you
Interface, is like a contract, which every other class which implements it has to follow

Why does Java allow multiple inheritance from interfaces but not from abstract/concrete classes [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why there is no multiple inheritance in Java, but implementing multiple interfaces is allowed
Why Java allows multiple inheritance from interfaces but not from abstract or concrete classes
Multiple inheritance of concrete classes raises a variety of issues.
For example, what if a class inherits two different implementations of the same method from two different base classes?
To avoid these issues, Java doesn't support this feature.
Unlike concrete classes, interfaces cannot have method bodies.
Therefore, none of these issues apply to interfaces.
Because implementing an interface is not inheritance. It simply means that your class will adhere to a predefined contract, typically to provide a set of methods related to a certain functionality. Any class can adhere to many such contracts without conflict (unless two of those interfaces define the same method).
Unlike inheritance, it does not automagically receive attributes or functionality due to a hierarchical relationship with its superclass since no such relationship exists.
Multiple inheritance is basically not allowed in Java or many other OO languages due to the already mentioned Diamond Inheritance problem.
I really don't like the term "inherit" here, it leads to a lot of confusion.
Java only allows interfaces to extend other interfaces, and for classes to implement interfaces.
If you look at an interface as a mathematical set of declarations, then each "extends" merely provides the union of the set from the superinterface and that of the current interface. You are therefore allowed to do multiple "unions".
When you eventually get to a class that implements one or more interfaces, the semantics here are merely that the class must provide implementations for all the methods in the set. A class implementing multiple interfaces could be rewritten as a class implementing a single interface that extends all the above interfaces.
In the case of classes inheriting multiple classes it is not allowed because it leads to a variety of problems, including the diamond problem. For instance, if I have two supertypes with different implementations of the same method signature, which one should be used in the subtype?
To make language simpler and more elegant. C++ allows a lots of stuff, but it's often pain to learn and use. We (me, at least :)) don't want java to be like that.

Categories