Interface:
- An interface is a structure that defines only the signatures (method signatures) of the methods a class must implement. In other words, it does not contain the method bodies (implementation), only specifying what needs to be done.
- A class can implement one or more interfaces.
- A class that implements an interface must implement all the methods defined in that interface.
- It is used to solve the problem of multiple inheritance.
Abstract Class:
- An abstract class is a class that can contain both abstract and concrete methods. This means some methods may be bodiless (abstract), while others may be implemented.
- A class can inherit from only one abstract class (single inheritance).
- Abstract classes cannot be directly instantiated (no instances can be created), but they can be extended by subclasses.
- They can contain both abstract and regular methods.
- Variables can be defined with any access modifier (public, private, protected).
- Subclasses are required to implement the abstract methods.
- Inheritance from multiple abstract classes is not possible.
Differences Between Interface and Abstract Class:
Criterion | Interface | Abstract Class |
---|---|---|
Method Type | Generally only method signatures (except default/static methods after Java 8). | Can have both abstract and concrete methods. |
Inheritance | Multiple interfaces can be implemented. | Only one abstract class can be inherited. |
Variables | Only public static final (constants). |
Variables of any type can be defined. |
Constructor | Cannot have a constructor. | Can have a constructor. |
Access Modifier | All methods are public by default. |
Methods can have different access modifiers. |
Purpose | Provides a fully abstract structure, typically used to define a set of behaviors. | Provides partial implementation, ideal for sharing common code. |
When Should We Use Which Structure?
-
Use an Interface:
- When you want to define a common behavior across multiple classes.
- When you want to achieve full abstraction between classes.
- When multiple inheritance is needed.
- Example: General behaviors like
Comparable
,Runnable
.
-
Use an Abstract Class:
- When you want to share common code (e.g., if some methods will have the same implementation).
- When you want to create a hierarchy between classes.
- When you need to use variables or concrete methods.
Thanks for reading.
Top comments (0)