Inheritance enables new classes to receive—or inherit—the properties and methods of existing classes.
Using two concepts of inheritance, sub classing (making a new class based on a previous one) and overriding (changing how a previous class works), you can organize your objects into a hierarchy. Using inheritance to make this hierarchy often creates easier to understand code, but most importantly it allows you to reuse and organize code more effectively.
In object-oriented programming, inheritance enables new objects to take on the properties of existing objects. A class that is used as the basis for inheritance is called a super class or base class. A class that inherits from a super class is called a subclass or derived class. The terms parent class and child class are also acceptable terms to use respectively. A child inherits visible properties and methods from its parent while adding additional properties and methods of its own.
class Person {
public function print_name($name) {
echo 'Name: ' . $name;
}
public function show_class() {
echo "Class Name: " . get_class($this);
}
}
class Student extends Person {
public function print_name($name) {
echo 'Student Name: ' . $name;
}
}
$person = new Person();
$student = new Student();
$person->show_class(); // Output: 'Class Name: Person'
$person->print_name('Zayn'); // Output: 'Name: Zayn'
$student->show_class(); // Output: 'Class Name: Student'
$student->print_name('Ali'); // Output: 'Student Name: Ali'
Sub classes and super classes can be understood in terms of the (is a) relationship. A subclass is a more specific instance of a super class. For example, an orange is a citrus fruit, which is a fruit. A shepherd is a dog, which is an animal. A clarinet is a woodwind instrument, which is a musical instrument. If the is a relationship does not exist between a subclass and super class, you should not use inheritance. An orange is a fruit; so it is okay to write an Orange class that is a subclass of a Fruit class.

0 comments:
Post a Comment