Junior
What is the essence of an abstract class?
sobes.tech AI
Answer from AI
The essence of an abstract class is to serve as a template for other classes. It cannot be instantiated directly but can contain abstract methods (without a body) that must be implemented in child classes, as well as concrete methods and properties.
Key points:
- Cannot create an instance:
new AbstractClass()will cause an error. - Inheritance: Only inheritance (
extends) is allowed from an abstract class. - Abstract methods: Define an interface that child classes must implement. Marked with the
abstractkeyword and have no body. - Concrete methods and properties: Can be defined and used directly, and overridden in child classes.
- Partial implementation: Provides a common structure and some basic functionality, leaving implementation details to the child classes.
Example:
<?php
abstract class Shape {
protected $color;
public function __construct($color) {
$this->color = $color;
}
abstract public function calculateArea(); // Abstract method
public function getColor() {
return $this->color;
}
}
class Circle extends Shape {
private $radius;
public function __construct($color, $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function calculateArea() {
return pi() * $this->radius * $this->radius;
}
}
class Square extends Shape {
private $side;
public function __construct($color, $side) {
parent::__construct($color);
$this->side = $side;
}
public function calculateArea() {
return $this->side * $this->side;
}
}
// Usage example
$circle = new Circle("Red", 5);
echo "Circle area: " . $circle->calculateArea() . ", Color: " . $circle->getColor() . "\n";
$square = new Square("Blue", 4);
echo "Square area: " . $square->calculateArea() . ", Color: " . $square->getColor() . "\n";
// The following code will cause a Fatal error: Instantiating an abstract class
// $abstractShape = new Shape("Unknown");
Comparison table with interfaces and regular classes:
| Characteristic | Abstract Class | Interface | Regular Class |
|---|---|---|---|
| Create instance | No | No | Yes |
| Inheritance | Yes (extends) + Implementation (implements) |
Only Implementation (implements) |
Yes (extends) |
| Methods | Concrete and abstract | Only abstract (without body) | Only concrete |
| Properties | Yes | No | Yes |
| Multiple inheritance | No | Yes | No |
| Purpose | Partial implementation, common structure | Contract definition (behavior) | Full implementation, concrete object |
Used when there is common logic and properties that should be in a group of related classes, but their specific behavior (implementation of some methods) varies. It provides code reuse and uniformity in class structure.