The difference between an interface and an abstract class in Java is fundamental to understanding Java's approach to abstraction and polymorphism, and it's a common topic in programming interviews.
Key Differences
Abstraction Level:
- Abstract Class: Can achieve partial abstraction (0 to 100%). It can have both abstract methods (which do not have a body) and concrete methods (which have a body).
- Interface: Achieves full abstraction (100%). Prior to Java 8, interfaces could only have abstract methods (no method bodies). From Java 8 onwards, interfaces can also have default and static methods with a body.
Method Implementation:
- Abstract Class: Can provide a default behavior and can also declare method implementations.
- Interface: Originally, interfaces could not provide method implementations. However, since Java 8, interfaces can provide implementations through default and static methods, but the primary intent is still to define methods that must be implemented by the classes that use the interface.
Constructor:
- Abstract Class: Can have constructors.
- Interface: Cannot have constructors because interfaces are not meant to be instantiated on their own.
Instance Variables:
- Abstract Class: Can have instance variables that can be non-final and non-static.