Tuesday, March 16, 2010

What is Inheritance

It is possible for a class to inherit another class as in the following example:
class MyDerivedClass: MyBaseClass
{
    // …
}
In this example, we declared the class MyDerivedClass, which inherits the class MyBaseClass. In the declaration, the colon (: ) is used between the name of the derived class and the name of the base class. Inheritance means that the derived class contains all the members of the base class. We can also add new members to the inherited members. For example, the Employee class inherits all the characteristics of the Person class and adds to them the characteristics of an Employee.
The following rules control inheritance:
1.    All members of the base class are inherited (except instance constructors, destructors, and static constructors).
2.    If we declare a member in the derived class with the same name as that in the base class, it hides the member in the base class. In that case, the member of the base class is not accessible through the derived class.
3.    Functions members in the base class can be overridden by those in the derived class, making it possible to exhibit polymorphism.
4.    In C#, a class can inherit from one class only. However, it can implement more than one interface. When a class implements an interface, it “inherits” its members.
5.    Structs cannot inherit from classes or other structs, but they can implement interfaces. They also cannot be inherited.
Note: - Sometimes the expressions specialization and generalization are used to express inheritance. For example, the Cow class specializes the Mammal class, and the Mammal class generalizes the Cow class. The base class is also referred to as superclass or parent class, and the derived class is referred to as the subclass or child class.
In the following example, the class Employee, which inherits from the class Citizen, is demonstrated.
Example: -
//Example 5-12.cs
//Inheritance example
using System;
class Citizen
{
    string idNumber = “111-2345-H”;
    string name = “Pille Mandla”;
    public void GetPersonalInfo()
    {
        Console.WriteLine(“Name: {0}”, name);
        Console.WriteLine(“ID Card Number: {0}”, idNumber);
    }
}
class Employee: Citizen
{
    string companyName = “Technology Group Inc.”;
    string CompanyID = “ENG-RES-101-C”;
    public void GetInfo()
    {
        //Calling the base class GetPersonalInfo method:
        Console.WriteLine(“Citizen’s Information: “);
        GetPersonalInfo();
        Console.WriteLine(“\nJob Information:”);
        Console.WriteLine(“Company Name: {0}”, companyName);
        Console.WriteLine(“Company ID: {0}”, companyID);
    }
}
class MainClass {
    public static void Main()
    {
        Employee E = new Employee();
        E.GetInfo();
    }
}
Notice in this example that all the member methods have the access level public. This is necessary for accessing the class fields.

No comments:

Post a Comment