How do abstract class and interface differ in object-oriented programming?
sobes.tech AI
Answer from AI
The differences between an abstract class and an interface in PHP are as follows:
-
Abstract class can contain both abstract methods (without implementation) and methods with implementation, as well as properties.
-
Interface only contains method declarations (starting from PHP 8, default implementations can be added, but this is a special case), and does not contain state (properties).
-
A class can inherit from only one abstract class, but can implement multiple interfaces.
-
An abstract class is used when you need to define a base implementation and a common contract, whereas an interface is used to define only a contract without implementation.
Example:
abstract class Animal {
abstract public function makeSound();
public function sleep() {
echo "Sleeping";
}
}
interface CanFly {
public function fly();
}
class Bird extends Animal implements CanFly {
public function makeSound() {
echo "Chirp";
}
public function fly() {
echo "Flying";
}
}
Thus, the abstract class provides a partial implementation, while the interface only defines a contract.