Junior — Middle
What is the main purpose of creating abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
The main purpose of abstract classes is to define a common template for a group of related classes, specifying the basic structure and behavior but not implementing all details. An abstract class cannot be instantiated directly; it serves as a base for inheritance and requires derived classes to implement certain methods. This helps ensure consistency and avoid code duplication.
Example in PHP:
abstract class Animal {
abstract public function makeSound();
public function sleep() {
echo "Sleeping...";
}
}
class Dog extends Animal {
public function makeSound() {
echo "Woof!";
}
}
$dog = new Dog();
$dog->makeSound(); // Outputs: Woof!
$dog->sleep(); // Outputs: Sleeping...