Inheritance
Inheritance is one of the most important features of OOPs programming. Inheritance means deriving attributes from one class to another. It improves reusability of the code. The user can write a new class by extending the existing class. That means a new class has features of both existing classes which is derived by the new class and also the additional feature defined by the new class itself. The new class is called a subclass and the existing class which is derived from subclass or child class is known as a superclass or parent class or base class. Let's understand the following diagram.
Now, let’s figure out the main point,
- Inheritance allows deriving a new class from an existing class. It improves the reusability of code.
- The existing class is called super, parent or base class.
- The new or derived class is known as child class or subclass.
- The child class inherits characteristics of a parent or superclass. It means data member and method defined in a superclass can be used by a child class.
- Only public and protected members (data and method) of the superclass can be accessed by the child class. No private member inherits by child class so they cannot be accessed by the child class.
- Protected member inherits by child class and only its decedents in the hierarchy.
- The child has also its unique behavior and characteristics. It means the child class has its own data member and methods.
- C# supports single level inheritance, multiple inheritances cannot be supported by C#. It can be achieved by the interface.
Let understand it with an example
- class A
- {
- int a;
- public void seta()
- {
- a = 400;
- }
- public int geta()
- {
- return a;
- }
- }
-
- class B : A
- {
- int b;
- public void setb()
- {
- b = 500;
- }
- public int getb()
- {
- return b;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- B ob = new B();
- ob.seta();
- ob.setb();
- Console.WriteLine("value of a="+ob.geta());
- Console.WriteLine("value of b=" + ob.getb());
- }
- }
Let’s understand why inheritance is so important.
As you see that we have two classes pEmployee for permanent employee and tempEmployee for a temporary employee. Both classes have similar data such as name, email, and mobile so we can say it's redundant in the code. We can take the common properties into a new class called the employee and then inherit employee into the pEmployefe and tempEmployee so that we can reduce redundant code and improve reusability which reduces the code and enhances testing.
Now, our code is well designed. The common attribute is placed inside employee class and that class is inherited into pEmployee and tempEmployee. Although both classes inherit employee class, still both can have their own data member or method as required.