Inheritance

This is one of the four pillars of OOP. Inheritance is when one object inherits or reuses another object's properties or methods. The class that gets inherited is called the base class and the class that inherits the base class is normally called the derived class. The inheritance relationship can be treated as an is a relationship. For example, pasta is a Food. The Pasta object has a unique ID in the database, which has other properties such as name, price, and chef. So, as Pasta satisfies all the attributes of the Food class, it can inherit the Food class and use the properties of the Food class. Let's look at the code:

public class Pasta : Food {
public string Type { get; set; }
public Sauce Sauce { get; set; }
public string[] Spices { get; set; }
}

The case is the same for beverages. For example, Coffee is a type of beverage that has all the attributes that the Beverage object has. A coffee has a name and price, and it might have sugar, milk, and coffee beans. Let's write the Coffee class and see how it looks:

public class Coffee : Beverage {
public int Sugar { get; set; }
public int Milk { get; set; }
public string LocationOfCoffeeBean { get; set; }
}

So here we can say that Coffee is inheriting the Beverage class. Here, Coffee is the derived class and Beverage is the base class.

In an earlier example, we used the Programmer object. In that case, do you think that the Programmer class can actually inherit the Human class? Yes, for sure. A programmer is nobody other than a human in this example. If we look at the properties of a Programmer and the properties of a Human, we will find that there are some common properties, such as the name, age, and so on. Consequently, we can modify the code of the Programmer class to resemble the following:

public class Programmer : Human {
// Name, Age properties can be inherited from Human
public List<ProgrammingLanguages> ProgrammingLanguages { get; set; }
public ProgrammerType Type { get; set; } // Backend/Frontend/Full Stack/Web/Mobbile etc

public bool WorkOnAProject(Project project, Computer computer){
// use the provided computer to do the project
// here we can see that the programmer is using a computer
}
}

Now let's see how we can draw a UML diagram for our Programmer class:

Inheritance is represented by a solid line with a triangle sign attached to it. This triangle points in the direction of the super class:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.128.145