TechnicalMedium OOP & Design
What is the difference between an interface and an abstract class?
Asked for Backend Developer, Full-Stack Developer, Mobile Developer
Why they ask this: Tests whether you can design flexible code rather than only reciting definitions.
Answer
| Interface | Abstract class | |
|---|---|---|
| Contains | method signatures (and constants) | abstract and implemented methods, plus properties |
| A class can use | many interfaces | only one parent class (in PHP, Java and Dart) |
| Constructor and state | no | yes |
| Meaning | "can do" (a capability) | "is a" (a shared base) |
- Use an interface to define a contract that unrelated classes can implement:
Cacheable,PaymentGateway. - Use an abstract class to share code between closely related classes that differ in a few steps, for example a
Reportbase class with an abstractrows()method.
In PHP you can combine both, and use traits to share code horizontally. Dart has no interface keyword in older versions: every class can be implemented with implements, and Dart 3 adds interface class.
Can you explain this in your own words?