Junior — Middle
What steps should be taken when using abstract classes in object-oriented programming?
sobes.tech AI
Answer from AI
When using abstract classes in object-oriented programming, the following steps must be taken:
-
Define an abstract class with the keyword
abstract. Such a class can contain both implemented methods and abstract methods (without implementation). -
Declare abstract methods within the abstract class — these are methods without a body that must be implemented in subclasses.
-
Create subclasses that inherit from the abstract class and implement all its abstract methods.
-
Use objects of subclasses to create instances, as the abstract class cannot be instantiated directly.
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 define a common interface and partial implementation, ensuring polymorphism and code reuse.