This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.
When wou
1.If you are creating something that provides common functionality to unrelated classes, use an interface.
2.If you are creating something for objects that are closely related in a hierarchy, use an abstract class.
If you are looking at java as OOP language,
"interface does not provide method implementation" is no longer valid with Java 8 launch. Now java provides implementation in interface for default methods.
In simple terms, I would like to use
interface: To implement a contract by multiple unrelated objects. It provides "HAS A" capability.
abstract class: To implement the same or different behaviour among multiple related objects. It establishes "IS A" relation.
Oracle website provides key differences between interface
and abstract
class.
Consider using abstract classes if :
Consider using interfaces if :
Serializable
interface.Example:
Abstract class ( IS A relation)
Reader is an abstract class.
BufferedReader is a Reader
FileReader is a Reader
FileReader
and BufferedReader
are used for common purpose : Reading data, and they are related through Reader
class.
Interface ( HAS A capability )
Serializable is an interface.
Assume that you have two classes in your application, which are implementing Serializable
interface
Employee implements Serializable
Game implements Serializable
Here you can't establish any relation through Serializable
interface between Employee
and Game
, which are meant for different purpose. Both are capable of Serializing the state and the comparasion ends there.
Have a look at these posts :
How should I have explained the difference between an Interface and an Abstract class?
The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.
Use an abstract class if you want to provide some basic implementations.
When to do what is a very simple thing if you have the concept clear in your mind.
Abstract classes can be Derived whereas Interfaces can be Implemented. There is some difference between the two. When you derive an Abstract class, the relationship between the derived class and the base class is 'is a' relationship. e.g., a Dog is an Animal, a Sheep is an Animal which means that a Derived class is inheriting some properties from the base class.
Whereas for implementation of interfaces, the relationship is "can be". e.g., a Dog can be a spy dog. A dog can be a circus dog. A dog can be a race dog. Which means that you implement certain methods to acquire something.
I hope I am clear.