Junior — Middle
Explain what abstract classes are in object-oriented programming.
sobes.tech AI
Answer from AI
An abstract class is a class that is not intended to be instantiated directly, but serves as a base class for other classes. It can contain both implemented methods and abstract methods (without implementation), which must be overridden in subclasses.
In PHP, an abstract class is declared using the abstract keyword. If a class contains at least one abstract method, it must be declared as abstract.
Example:
abstract class Animal {
abstract public function makeSound();
public function sleep() {
echo "Sleeping...";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Bark";
}
}
$dog = new Dog();
$dog->makeSound(); // Outputs "Bark"
$dog->sleep(); // Outputs "Sleeping..."
Abstract classes help create a common interface and basic functionality for a group of related classes.