What is the difference between an abstract class and an interface?
EasyConceptOOP & SOLID
Answer
An abstract class is a partially implemented base class that can hold state, constructors and concrete methods, and a class can extend only one. An interface is a contract of methods that unrelated classes can implement, and a class can implement many.
- Use an abstract class when subclasses share common state or code, such as a
Vehiclewith alicensePlatefield and shared validation. - Use an interface to describe a capability, such as
ComparableorPayable, across unrelated types. - Java detail: since Java 8, interfaces can have
defaultandstaticmethods, but they still cannot hold instance fields. - C++ has no interface keyword; an abstract class containing only pure virtual functions plays that role, and multiple inheritance is allowed.
More in OOP & SOLID
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What are the four pillars of object-oriented programming? | Concept | Easy | Read the answer to What are the four pillars of object-oriented programming? | |||
| 2 | What is the difference between an abstract class and an interface? | Concept | Easy | Read the answer to What is the difference between an abstract class and an interface? | |||
| 3 | What are the SOLID principles? | Concept | Medium | Read the answer to What are the SOLID principles? | |||
| 4 | Why is composition often preferred over inheritance? | Concept | Medium | Read the answer to Why is composition often preferred over inheritance? |