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
Related
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 8 years ago.
I haven't done OOP in a while so I'm a bit rusty.
For an example, i have a client with a rental subscription, and it exist 3 type of subscription. How can i choose between abstract class and interface for my "Subscription" class?
Each subscription must have the price, maximum Rental Duration and maximum Rental Count.
From what I remember, I would use interface here but how can I force other classes that implements subscription to specify the value(constant) of these 3 properties?
If you're thinking of defining fields that are common to all implementations, you can't use an interface, because an interface does not contain state. It can just declare methods and constants. State is considered part of an implementation, not type information.
You could, however, define three abstract getter methods - getPrice(), getDuration() and getCount() or something like that, and leave the actual implementation of how those work to the implementing classes. In that case, you could use either an interface or an abstract class.
You'd choose an abstract class if you have some implementation that you want to have which is common to all subclasses. For example, if you have a specific way to perform "rent out", or "send reminder to renter" or other operations. Those methods will be concrete, and only the above three getters will be abstract.
If you don't have any common operations, and you find yourself just having the abstract methods and nothing else, an interface will probably serve you best, especially so because Java is single-inheritance, and using an interface will allow you to extend another class when you are creating your concrete classes.
These are just rules of thumb, though, not rules set in stone.
I think an abstract class makes more sense in this case. Use abstract classes when your classes all deal with the same data/methods but may slightly differ in method logic.
Interfaces may be more useful when you have several classes which have large differences but should always be constrained to a set of methods(the interface methods)
In general you use abstraction in case of inheritance and polymorphism. When you have an object that can have different behavior based on its internal type. Interfaces are used when there is a need for a contract. In general abstraction is best for objects that are closely related, while interfaces are chosen for their functionality.
In your case abstraction makes sense. You can keep the mutual properties in your base class and derive other classes from it. Eliminates some redundant code.
Here is what MS suggested:Here are some recommendations to help you to decide whether to use an interface or an abstract class to provide polymorphism for your components.
*If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
*If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
*If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
*If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.
https://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx
This question already has answers here:
Interface vs Abstract Class (general OO)
(36 answers)
Closed 9 years ago.
After searching through google and reading a lot of stuff , I conclude that I may able to decide when to use Interface and when to use abstract class except
If all the methods are abstract and public and in future no need to add any method.
So I want to know what option (Interface or Abstract Class) I use if the above condition arises.
Java doesn't support multiple inheritance so we can only extends one class, there for it is better to use interfaces. But depending on a situation this can be differ. My opinion as a best practice, interface better than abstract class most of the time.
You want to use an interface if you have to define a set of common behaviour on different entities.
You use an abstract class if you want to differ between related entities that share common functionality. The abstract class can then hold the common functionality and define the abstract methods that should be used by subclasses to define their specific behaviour.
Keep in mind though that a class can only extend one other class, but it can inherit from multiple interfaces.
If all the methods are abstract and public and in future no need to add any
method
In Interfaces all functions are by default public and abstract whereas an abstract class can have non abstract methods. So you have your answer!
Abstract classes are best used when they carry behaviour with them in form of implemented methods which´s functionality is usefull for child classes.
In your case, you should go for an interface.
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
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.
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.