Both abstract classes and Interfaces are abstraction mechanism of java programming language. But they have some differences as shown below :
|Variables||It can have both final and non-final variables. |
It can have both static and non-static variables.
It can have variables with any access modifers.
|All variables are implicitly public, final and static.|
|Methods||Methods inside an abstract class can have any of the access modifiers.|
It can have abstract as well as concrete methods.
|All methods are implicitly public(even default and static methods)
All non-default and non-static methods are implicitly abstract.
|Constructors||It can have constructors.||It cannot have Constructors|
|Access modifiers||An abstract class can have any access modifier.||An outer interface can be either public or can have default access level.
A nested interface can have any access modifier.
|Inheritance||A class can extend only one class.||An interface can extend any number of interfaces.
A class can implement any number of interfaces.
|Keyword||abstract keyword is used to define an abstract class.||interface keyword is used to define an interface.|
|Miscellaneous features||An abstract class can implement an interface.||An interface cannot implement or extend an abstract class.|
1. Which should you use: Abstract classes or Interfaces?
Both abstract classes and interfaces have some differences and some similarities. So there is some confusion about when to use an abstract class and when to use an interface.
1.1 When to use abstract classes
Consider using abstract classes in following situations:
- When you want to share code among several closely related classes.
- When you want to have non-static or non-final variables.
- If classes that extend your abstract class require access modifiers other than public (such as protected and private).
1.2 When to use Interfaces
Consider using interfaces in following situations:
- If you want to use multiple inheritance.
- If you expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
- If you want to specify the behavior of a particular method, but not concerned about who implements its behavior.
Visit this page to know more about the differences.