Understand inheritance in OOP

This article aims to make you understand what inheritance in object-oriented programming. You will also understand, through some examples, what overriding methods...

Understand inheritance in Object Oriented Programming


Here is a new post that will try to make you discover, for example, what inheritance in OOP , but first, a little reminder :

What is inheritance ?

The word inheritance is often used in a context of sucession or genetics. It implies that the descendants possess some of the genes or property of their ancestors.

And in oriented programming language ?

For newbies, we can define what is l'inheritance en POO (Object oriented programming) :

Basically, it is a mechanism that will permetttre, as its name suggests, to transmit all the methods of a class called "mother" to another so-called "daughter" and so on.

Take a typical example with three class :

Mother class :

// This "mother" class is destined to host all
// methods that are common to all persons
class Person
    public Sex $sex;

    public function __construct(Sex $sex)
        // Here we can define some specific methods 
        // to this instance of this person

    public function walk()
       // Here, we can define what is the invocation to the method walk
       // $this->raiseFoot(); // For example
       // $this->layFoot();

    public function sleep()
        // What is sleep

    public function getSex()
        return $this->sex;

    public function setSex(Sex $sex)
        $this->sex = $sex;

First daughter class :

// This "daughter" class will have all specific methods of this mother
// Unless we need to explicitly re-specify them
class Developper extends Person
    // This is specific to developper
    public $langage;

    public function __construct(Sex $sex)
        // We call "mother" constructor
        // to specify this parameter to our instance
        // This method will call setSex($sex) of 
        // "mother" class internally

    public function develop()
        // We can do specific actions to developper

Second daughter class (or "granddaughter") :

// This class will have all methods of his "mother" class,
// developper class
class PhpDevelopper extends Developper
    // ... Same for constructor

    // This is an example of overriding
    // @See https://secure.php.net/manual/en/language.oop5.overloading.php
    public function develop($language = 'PHP')
        // Define language and default 
        $this->language = $language;


We see here that each subclass inherits all the properties and methods that we wish his mother class (via the visibility).

It's actually as if we could choose what types of genes we could have our descendants !!!

See you soon,

Weenesta web agency

Posted in Tutorials on Oct 17, 2017

Tags list

  • symfony (2)
  • api (2)
  • web-service (2)
  • inheritance (2)
  • php (2)

Related posts


Post a reply

1-0 of 0

Reply to discussion

You can't replay: Not Logged in.