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

InterfaceAbstract class
Containsmethod signatures (and constants)abstract and implemented methods, plus properties
A class can usemany interfacesonly one parent class (in PHP, Java and Dart)
Constructor and statenoyes
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 Report base class with an abstract rows() 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?

Back to question bank