In the last article we talked about OOP briefly. Just trying to understand the concept and the relationship between an object and a class. If you haven’t read that I advise you to. This is the link to that article here. It will help to grab better what is in this article. So lets us jump into the business of today. We want to look into Inheritance one of the the four pillars of OOP.
Inheritance allows us to create classes that have derived attributes from another existing class. The idea behind inheritance is that a class (child class) can acquire/inherit attributes from another existing class (parent class). This was used as a way for re-using code. Let’s us look at an example. So let us continue from where we stopped in the previous post. we have an existing class called class Person
public class Person
{
public string Name { get; set; }
public string Job { get; set; }
public string Height { get; set; }
public string Weight { get; set; }
public string Walking()
{
return "I am Walking";
}
public string Sleeping()
{
return "I am sleeping";
}
}
Let us create another class called father and consider these code snippets
public class Father:Person
{
public bool IsEmployed { get; set; }
public string[] KidsNames{ get; set; }
public string Wife { get; set; }
}
In the above the syntax of :Person
is how inheritance works. What we are saying here is that the father class inherits from the Person class
class Program
{
static void Main(string[] args)
{
//create an instance of that class
Person person = new Person();
Father father = new Father();
//instantiate the values in that class
person.Job = "Banker";
person.Name = "Jacob";
person.Height = "5,3";
person.Weight = "65kg";
// All these are the inherited attributes from the class person
father.Height = "5,3";
father.Name = "Richard";
father.Weight = "70kg";
father.Job = "SalesMan";
//These are the attributes specific to the class father
father.IsEmployed = true;
father.Wife = "Sandra";
father.KidsNames = new string[] { "Ayo", "Prosper", "David" };
//Display them on the screen
Console.WriteLine(person.Weight);
Console.WriteLine(person.Height);
Console.WriteLine(person.Job);
Console.WriteLine(person.Name);
Console.WriteLine(person.Sleeping());
Console.WriteLine(person.Walking());
Console.WriteLine(father.Weight);
Console.WriteLine(father.Height);
Console.WriteLine(father.Job);
Console.WriteLine(father.Name);
Console.WriteLine(father.Wife);
Console.WriteLine(father.Sleeping());
Console.WriteLine(father.Walking());
}
As we can see we created an instance of the father class and this instance has the father class attributes and the Person parent class attribute.
There is more to inheritance like multi-level inheritance where a sub class will act as a parent class for another subclass and multiple inheritance where a class can inherit from multiple parent classes. I try to keep my explanations short and straight-forward. I will like to hear your comments on the article
Top comments (0)