Junior
What is the purpose of using an abstract class in programming?
sobes.tech AI
Answer from AI
An abstract class is used to define a common interface and a base implementation for a set of related classes (subclasses). It cannot be instantiated directly but can contain both abstract methods (without implementation, which must be implemented in subclasses) and regular methods with implementation.
Main goals:
- Defining a contract: Specifies a set of methods that must be implemented by all subclasses, ensuring consistency in their behavior.
- Preventing instantiation: Ensures that only specific classes implementing the abstract class can be used in the program.
- Centralizing common code: Contains shared methods and properties used by multiple subclasses, avoiding code duplication. Example:
<?php
// Abstract class "Animal"
abstract class Animal {
protected $name;
public function __construct(string $name) {
$this->name = $name;
}
// Abstract method to be implemented by subclasses
abstract public function makeSound(): string;
// Regular method
public function getName(): string {
return $this->name;
}
}
// Concrete class "Dog" inheriting Animal
class Dog extends Animal {
public function makeSound(): string {
return "Woof!";
}
}
// Concrete class "Cat" inheriting Animal
class Cat extends Animal {
public function makeSound(): string {
return "Meow!";
}
}
// Cannot instantiate an abstract class
// $animal = new Animal("General"); // Error!
$dog = new Dog("Bobby");
echo $dog->getName() . " makes sound: " . $dog->makeSound() . "\n"; // Bobby makes sound: Woof!
$cat = new Cat("Murka");
echo $cat->getName() . " makes sound: " . $cat->makeSound() . "\n"; // Murka makes sound: Meow!