Junior — Middle
Can you list the key advantages and features of abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
Abstract classes in object-oriented programming possess the following key advantages and characteristics:
- Cannot instantiate: An abstract class serves as a template and cannot be instantiated directly.
- Interface definition: Allows declaring abstract methods that must be implemented in subclasses.
- Providing common functionality: Can contain both abstract and concrete methods, offering a base implementation for inheritors.
- Polymorphism support: Enables working with subclass objects through a reference to the abstract class.
Example in PHP:
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...
Thus, abstract classes help structure code by ensuring the implementation of key methods in subclasses and reducing code duplication.