When to use Interface and when to use Abstract class [duplicate] - java

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 8 years ago.
Folks can you explain me in which condition I should go with Interface and at which condition should I prefer Abstract class ... ? keep in mind I am not asking difference between Interface and Abstract class.

If you found any Is a relationships between objects you can use abstract
for example: Bird, Aeroplane, Paper Rocket these all are flyable but there is no any Is a relationship between these objects, so you can use here interface instead of abstract,
Because Bird,Aeroplane and Paper Rocket all are flyable but the way of flying is different.
And off course lots of differences are on Google.

Use Abstract class when : You have some common functionality (method) which must be implemented at only one place and other concrete classes can just use it.
Use Interface when : There is no common functionality. Every concrete class has its own implementation of functionality.

I would suggest to stick to the following rules:
use an abstract class only, if you need code-reuse
restrict the visibility to the package the abstract class is defined
Otherwise use an interface and delegation. But as it is with software design you have to make the proper decision for each concrete situation. If you have restriction / rules which must be applied but need some flexibility, think about using the strategy-pattern in preference to inheritance.
The problem with abstract classes is that you can't inherit from more then one. Hence, if you need a type which is of type A and B and both are abstract classes, how do you achieve this? Interfaces are open to be implemented by any other type without restrictions.

We must preferred first to inferface. If we have to write some common functionality in that class then and only then you can go for abstract class. Otherwise use interface. Because We can implement number of interface but we can extend only one class so for future you must go for interface rather than abstract class.

Related

What should I use Interface or abstract class? [duplicate]

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.

When shall we go for interface or abstract class in Java? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When to use an interface instead of an abstract class and vice versa?
Can any one tell me under which circumstances we should go for interface and abstract class.
Java specific aspects are welcome.
Always use an interface unless you need to ...
... provide subclasses with some state
... provide subclasses with default implementations of some methods
... want to defer implementation of some of the abstract methods
Note that you can only extend one class, while you can implement multiple interfaces. So if there's any chance that a subclass will need to extend some other class, strive for using an interface.
Here are some good links that discusses this topic:
Java World: Abstract classes vs. interfaces
Interface vs Abstract Class (general OO)
Abstract Class versus Interface
Mindprod: Interfaces vs Abstract classes
In simple Language :
Use interface if you want your objects be accessed by common way.
Use abstract class if you want to define some functionality in super class and to define prototype of some methods that must be override in child classes i.e., extending the functionality of a class.
Here is a funny example that might help you to clear the fundamentals.
http://ganeshtiwaridotcomdotnp.blogspot.com/2011/05/understanding-importance-of-interface.html
If you don't want to implement any method and you just want to define your contract, then you use an interface.
However, if you do want to have some implementation already, you should use an abstract class.
You will use an abstract class if you want to provide a partial implementation for the subclasses to extend, and an interface if you only want to provide signatures of methods that must be implemented.
It is perfectly normal to provide both and interface and an abstract class that implements parts of it.
There is however one limitation of abstract classes: In a subclass you can only extend one (abstract) class, but you may implement as many interfaces as you like in a single class.
Interfaces are simply a collection of public method signatures and public static final fields. No constructors, no protected/internal methods, no other type of fields.
On the other hand, any class can be abstract simply by putting abstract in front of its declaration. They can declare abstract methods and implement interfaces and other abstract classes without defining the method implementation.
An abstract class is more restrictive when it comes to inheritance (only one can father a subclass), but you can implement methods and constructors in it.
Any number of interfaces can be implemented by a class, but there is no default method & constructor implementation.
That is why it is always a good idea to provide an abstract class next to an interface as a default implementation option.
Check these
http://www.javaworld.com/javaworld/javaqa/2001-04/03-qa-0420-abstract.html
Abstract class and interface

When to use an abstract class? An interface? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Interface vs Abstract Class (general OO)
I am little bit familiar with the terms Abstract class and the interface.
But i want to know in which situation i have to use the interface and in which condition the abstract class.
Thanks
Interface vs Abstract Class should be a useful read.
In short, Abstract Classes are meant to be extended, as in you're giving someone a base to work off of. Interfaces ensure that things have a common way of interacting with one another without having to worry about the inside details.
Simple answer: you can implements many interfaces, but can only inherit from one class, so if you want to inherit some logic, you should use Abstract Class, otherwise Interface is more extensible.

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.

Do/can abstract classes replace interfaces? [duplicate]

This question already has answers here:
When to use an interface instead of an abstract class and vice versa?
(26 answers)
Closed 5 years ago.
In Java, you can create an abstract class that contains only abstract methods. On the other hand, you can create an interface that declares the same methods. That being the case, can you use abstract classes instead of interfaces?
Not always:
a class can extend only one class
a class can implement more than one interface
Sun docs make a more detailed comparison:
Abstract Classes versus Interfaces
Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods. Such abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead.
Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether or not they are related to one another in any way. Think of Comparable or Cloneable, for example.
By comparison, abstract classes are most commonly subclassed to share pieces of implementation. A single abstract class is subclassed by similar classes that have a lot in common (the implemented parts of the abstract class), but also have some differences (the abstract methods).
In some cases you can use an abstract class instead of interface. However, it is hardly ever a good idea to do so. In general you should use the rule:
Interfaces specify behaviour.
Abstract classes specify implementation.
The other "problem" with using abstract classes is that you can then no longer implement mixins, that is you can implement multiple interfaces, however you can only extend one abstract class.
One point missing from the answers here is the idea of who will be implementing the interface.
If your component wants to return instances of abstract types to its callers, where the concrete types are defined internally and hidden from callers, use an interface. Conversely, if your component consumes or accepts instances of abstract types that its callers must implement, abstract classes are usually a better choice.
Anticipating evolution and maintaining binary compatibility tips the scales here. With an abstract class, you can add methods and, if you provide a base implementation, existing implementations of the abstract class will continue to work fine. With an interface, adding a method breaks binary compatibility, for no existing implementation could possibly continue to compile properly without changing to define the new method.
The Apache Cactus project has a good discussion on how to resolve these obligations.
To answer your question, yes you could use an abstract class (providing no implementation) instead of an interface but I'd consider this bad practice:
You've used up your "one-shot" at inheritance (without gaining any benefit).
You cannot inherit from multiple abstract classes but you can implement multiple interfaces.
I would advocate the use of abstract classes more in situations where you wish to provide a partial implementation of a class, possibly delegating some behavior to concrete subclass implementations.
A class in java can inherit from multiple interfaces, but only from one abstract class.
An interface cannot define any code, in an abstract class, you can define code (i.e. default behaviour of methods)
Abstract classes and interfaces are complementary.
For instance when creating an API you will want to present interfaces to the client, so that you may always completely change the implementation whereas he does not have to change its code and the user does not rely on implementation when building using your API but just on methods contracts.
Then you will have abstract classes partly implementing these interfaces, in order to
share some common code, which might be used in all (or almost all) implementations for interface, which is obvious
provide default behaviour which could be overridden in 'real' implementations, for instance a toString() method using interfaces methods to create a textual representation of the implementation
preserve implementations compatibility after interface changes, for instance when you add a new method in your interface, you also add a default implementation in the abstract class so that implementations (for instance those made by the user) extending the abstract class still work without changes
Interfaces are much cleaner and light weight. Abstract classes make you dependent on it heavily as you cannot extend any other classes.
Have a look at the interesting article "Why extends is evil" to get an idea about the differences between interface implementation and class inheritance (beside the obvious multi- single restrictions)
Abstract classes are the partial implementation of Abstraction while Interfaces are the fully implementation of Abstraction.Means in Abstract classes we can put methods declaration as well as method body.
We can't create an object of Abstract classes(association) and reuse the class by inheritence(not by association).
By default in interfaces all declared variables are static final and All methods are public.
For Example: In JDK there are only few abstract classes and HttpServlet is one of them which is used in Servlet.So we can't create object of HttpServlet and it can be used only by inheritence.
Main use of interface is when you create the reference of interface and call the method of particular class that's resolved at runtime. So it's always better idea to create reference of interface to call the method.
Interfaces can only hold abstract method, also interfaces can implement multiple interfaces to any class. But an abstract hold abstract and non abstract methods, and abstract methods cannot extend to more then one class.

Categories