What is the main difference between an interface and an abstract class in Java?
Options
- There is no real difference, as both define methods
- A class implements many interfaces but extends one class (Correct option)
- Interfaces can have instance fields; abstract classes cannot
- Abstract classes cannot contain any method with code
Answer
A class can implement many interfaces but extend only one class; an abstract class can hold state (fields) and constructors
Why
An interface is a contract: a list of methods a class promises to provide (implements). A class can implement as many interfaces as it wants.
An abstract class is a half-built class that can have fields, constructors and some ready methods plus some abstract methods to complete. A class can extend only ONE class.
Since Java 8 interfaces can also have default methods with code, but they still cannot keep per-object state.
Remember
Many interfaces, one parent class. Only abstract classes carry state.