Difference Between Abstract Class and Interface
| Feature | Abstract Class | Interface |
|---|---|---|
| Instantiation | Cannot be instantiated directly (only through subclassing). | Cannot be instantiated (must be implemented by a class). |
| Methods | Can have both abstract and concrete methods. | - Prior to Java 8: Can only have abstract methods. - From Java 8: Can have default and static methods. - From Java 9: Can have private methods for internal use within the interface. By default, methods are public and abstract unless otherwise specified. |
| Variables | Can have instance variables (need not be public, static, or final). | By default, all variables are public static final.Must be initialized at the time of declaration. |
| Fields | Can have instance variables, just like a regular class. | Can only have constants (static final fields). |
| Constructors | Can have constructors (used to initialize instance variables). | Cannot have constructors (as they cannot instantiate objects). |
| Multiple Inheritance | Can extend only one class (abstract or concrete). | Can implement multiple interfaces (a class can implement many interfaces). |
| Inheritance | Use the extends keyword for subclassing. | Use the implements keyword for implementing an interface. |
| Default Behavior | Can provide default behavior for subclasses using concrete methods. | Cannot provide default behavior prior to Java 8. From Java 8, interfaces can provide default methods. |
| Access Modifiers | Methods can have any access modifier (private, protected, public). | Methods are implicitly public unless declared as private (Java 9+). Interfaces cannot have protected methods. |
| Object Creation | Can create reference variables and objects of the subclass. | Can only create reference variables, not objects. Cannot instantiate an interface. |
| Level of Sharability | Provides less sharability than interfaces. | Provides more sharability. Interfaces allow a class to inherit behaviors from multiple sources, providing more flexibility in multiple inheritance. |
| Fields Initialization | Instance variables are not required to be initialized at the time of declaration. | All variables in an interface must be initialized at the time of declaration. |
| Modifiers Restrictions | No restrictions for method modifiers. Methods can be private, protected, final, static, synchronized, etc. | Interface methods cannot have modifiers like private, protected, final, static, synchronized, or strictfp (except from Java 9+, which allows private methods for reuse within the interface). |
| Usage Scenarios | Used when some default behavior or common state needs to be shared between classes. | Used for defining a contract (i.e., what the implementing class must do) without dictating how it should be done. |