Language: EN

que-es-y-cuando-usar-herencia-en-programacion

What is and how to use object inheritance

The HERITAGE is a mechanism that allows for the creation of new classes based on existing classes. This facilitates code reuse and the organization of classes in hierarchies.

In this context, “inheriting” means that classes (or types) have some of the characteristics of the classes they inherit from. Just like in biological sense 👪.

Inheritance: This child has inherited the same hair as their mother!

In programming, inheritance is a mechanism by which some classes can copy attributes and methods from another class.

We will call,

  • Child class or subclass: The class that inherits
  • Parent class or superclass: The class from which it inherits

For example, if we have a class Animal as the parent class, we could have child classes like Dog, Cat, Bird, Cow, etc.

curso-poo-vaca

You can’t talk about inheritance in OOP without mentioning a cow

In addition to copying the methods from the parent class, the child class can add new attributes or methods, or even override those it inherits (otherwise inheritance wouldn’t be very interesting).

In this way, a child class can extend and specialize the behavior of the parent class. It copies part of the behavior but adds “its own details” and customizations.

When to use inheritance

The most common way to identify that we have a case of HERITAGE between classes is to detect that they share common code and we want to avoid copying it.

For example, let’s imagine we are working on a school management system. We have a class Person

class Person
{
	string Name;
	string Surname;
	// many more things
}

Now we need the classes Student, Teacher, Guardian, Principal. But they all have Name and Surname. So, instead of copying it, we can make them inherit.

class Student    extends  Person
class Teacher    extends  Person
class Guardian   extends  Person
class Principal   extends  Person

Just with that, our four child classes Student, Teacher, Guardian, Principal have Name and Surname available because they inherit them from Person.

// type Student inherits from Person
class Student
{
	// 👇 this one has it, without needing to define it
	// string Name;
	// string Surname;
}

Indeed, avoiding code repetition is one of the main purposes of inheritance. Therefore, it is one of the first indicators that we may have a case of inheritance.

But, things are much more interesting. The real reason for using inheritance is to identify that we have a specification of the parent class (a specification is a more concrete case of a concept).

That is, Person is a broader concept than Student or Teacher. These students and teachers are particular cases of people, but THEY ARE people.

Inheritance is a relationship where the child class is a more specific version of the parent class. You can detect it if you can build a sentence that contains “is a”.

For example:

  • A teacher is a person
  • A bird is an animal
  • A car is a vehicle
  • A shoe is a product

Example of Inheritance in different languages

Let’s see how the syntax for inheritance between classes would look in different programming languages.

curso-poo-figuras

Another classic example of OOP, triangles and circles

Let’s imagine that you have to draw geometric shapes on a 2D video game monitor. For that, we have a parent class Shape. From it inherit Rectangle, Circle, and Triangle.

In C#, inheritance is achieved using the : symbol. When inheriting one class from another, the child class acquires all the fields and methods of the parent class.

// parent class
class Shape
{
    public Point2D Position;
    public int Rotation;
    public int Width;
    public int Height;
}

// child classes that inherit
class Rectangle : Shape { }
class Circle : Shape { }
class Triangle : Shape { }

In C++, inheritance is implemented using the public keyword followed by :. This public inheritance relationship allows the public members of the base class to be accessible in the derived class.

// parent class
class Shape
{
public:
    Point2D Position;
    int Rotation;
    int Width;
    int Height;
};

// child classes that inherit
class Rectangle : public Shape {};
class Circle : public Shape {};
class Triangle : public Shape {};

In JavaScript, inheritance is achieved using the extends keyword, which allows a child class to inherit from a parent class.

// parent class
class Shape {
    constructor() {
        this.Position = new Point2D();
        this.Rotation = 0;
        this.Width = 0;
        this.Height = 0;
    }
}

// child classes that inherit
class Rectangle extends Shape { }
class Circle extends Shape { }
class Triangle extends Shape { }

In Python, inheritance is achieved by placing the name of the base class in parentheses after the name of the child class. This indicates that the child class inherits from the base class.

Because Python is like that and you have to love it as it is (I suppose)

# parent class
class Shape:
    def __init__(self):
        self.Position = Point2D()
        self.Rotation = 0
        self.Width = 0
        self.Height = 0

# child classes that inherit
class Rectangle(Shape):

class Circle(Shape):

class Triangle(Shape):

In all these examples, the child classes Rectangle, Circle, and Triangle have all the attributes and methods of the parent class Shape because they inherit from it.

Where does inheritance come from?

Why was the concept of HERITAGE invented, as a fundamental part of Object-Oriented Programming? Let’s go back to basics and remember that at that time, it was already common to have groupings of variables that abstracted concepts.

pilares-oop

The four pillars of OOP

However, anyone could come and modify anything. Basically, you could have a Shape object, and by changing its shapes, make it work for a rectangle, a circle, or a triangle.

But as we said, this led to unmanageable messes. This is why Object-Oriented Programming places ENCAPSULATION as one of its pillars. With this, no one could come and modify an object.

Now they had “armored” the OBJECTS, they could no longer be modified as before. Now you necessarily had to repeat the code for Rectangle, Circle, and Triangle, each with all the complete code. It wasn’t very desirable either.

For that reason, the HERITAGE was invented. To allow a mechanism that would let us reuse code between classes, so that it wouldn’t have to be copied over and over again.

But this time, doing it in a regulated and controlled way, corresponding with a relationship of kinship.