What is the difference between an interface and an abstract class

An interface and an abstract class are both tools in object-oriented programming that allow you to define methods that must be implemented in derived classes. However, they serve different purposes and have distinct characteristics.

Key Differences

  • Definition: An interface is a contract that defines a set of methods without implementing them, while an abstract class can have both fully implemented methods and abstract methods.
  • Multiple Inheritance: A class can implement multiple interfaces but can inherit from only one abstract class.
  • Access Modifiers: Methods in an interface are implicitly public and cannot be private or protected. In contrast, an abstract class can have methods with any access modifier.
  • State Management: Abstract classes can have member variables and maintain state, while interfaces cannot hold any state.

Example

// Defining an interface interface Vehicle { public function start(); public function stop(); } // Defining an abstract class abstract class Car { protected $color; public function __construct($color) { $this->color = $color; } abstract public function drive(); public function getColor() { return $this->color; } } // Implementing the interface class Tesla extends Car implements Vehicle { public function start() { echo "Tesla starting...\n"; } public function stop() { echo "Tesla stopping...\n"; } public function drive() { echo "Driving a {$this->color} Tesla!\n"; } }

interface abstract class object-oriented programming multiple inheritance access modifiers state management