Inheritance in Depth
Inheritance in depth is the study of how a child class reuses, replaces and locks the methods of its parent. An override is a child method that replaces a parent method with the same name.
A child override replaces the parent method
Car overrides the describe method of Vehicle. The same call shape prints the parent line on the parent object and the child line on the child object.
<?php
class Vehicle {
public function describe() {
echo "A vehicle moves\n";
}
}
class Car extends Vehicle {
public function describe() {
echo "A car drives\n";
}
}
$vehicle = new Vehicle();
$vehicle->describe();
$car = new Car();
$car->describe();parent:: runs the parent version too
The Car override calls parent::describe() first. Both lines print, so the parent version and the child line both ran.
<?php
class Vehicle {
public function describe() {
echo "A vehicle moves\n";
}
}
class Car extends Vehicle {
public function describe() {
parent::describe();
echo "A car drives\n";
}
}
$car = new Car();
$car->describe();A final method is used as it is
The wheels method of Vehicle is marked final. Car adds no override, so the Car object runs the parent version unchanged.
<?php
class Vehicle {
final public function wheels() {
echo "Wheels turn\n";
}
public function describe() {
echo "A vehicle moves\n";
}
}
class Car extends Vehicle {
}
$car = new Car();
$car->wheels();
$car->describe();Example
<?php
class Animal {
public function sound() {
echo "Some sound\n";
}
final public function describe() {
echo "An animal with a sound\n";
}
}
class Dog extends Animal {
public function sound() {
echo "Woof\n";
}
}
$animal = new Animal();
$animal->sound();
$dog = new Dog();
$dog->sound();
$dog->describe();Key points
- An override replaces the parent method for child objects.
- The override keeps the same method name as the parent method.
- parent:: calls the parent version from inside the child.
- The word final before a method stops children from overriding it.
- A child that tries to override a final method stops the program with a fatal error.
- A final method still runs in child objects as written in the parent.
In this example, the Animal class gives a plain sound method and a final describe method. Dog overrides sound, so the dog object prints Woof. The describe call runs the final parent version, since no child may replace it.
Note
A whole class can be marked final too, and then no class can extend it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A child class writes a method with the same name as a method in its parent. What is that child method called?