C Sharp Programming/Inheritance

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

Contents

[edit] Inheritance

Inheritance is the ability to create a class from another class, the "parent" class, extending the functionality and state of the parent in the derived, or "child", class.

Inheritance in C# also allows derived classes to overload methods from their parent class.

[edit] Subtyping Inheritance

The code sample below shows two classes, Employee and Executive. Employee has the following methods, GetPayCheck and Work.

We want the Executive class to have the same methods, but differently implemented and one extra method, AdministerEmployee.

Below is the creation of the first class to be derived from, Employee.

public class Employee
   {
       // we declare one method virtual so that the Executive class can
       // override it.
       public virtual void GetPayCheck()
       {
           //get paycheck logic here.
       }
 
       //Employee's and Executives both work, so no virtual here needed.
       public void Work()
       {
           //do work logic here.
       }
   }

Now, we create an Executive class that will override the GetPayCheck method.

public class Executive : Employee
   {
       // the override keyword indicates we want new logic behind the GetPayCheck method.
       public override void GetPayCheck()
       {
           //new getpaycheck logic here.
       }
   
       // the extra method is implemented.
       public void AdministerEmployee()
       {
           // manage employee logic here
       }
   }

You'll notice that there is no Work method in the Executive class, it is not required, since that method is automatically added to the Executive class, because it derives its methods from Employee, which has the Work method.

static void Main(string[] args)
       {
            Employee emp = new Employee;
            Executive exec = new Executive;
       
            emp.Work();
            exec.Work();
            emp.GetPayCheck();
            exec.GetPayCheck();
            exec.AdministerEmployee();
       }

[edit] Virtual Methods

If a base class contains a virtual method which it calls elsewhere and a derived class overrides that virtual method, the base class will actually call the derived class' method:

public class Resource : IDisposable
{
    private bool closed;
 
    protected virtual void Close()
    {
        Console.WriteLine("Base resource closer called!");
    }
 
    ~Resource()
    {
        Dispose();
    }
 
    public void Dispose()
    {
        if (!closed)
        {
            Console.WriteLine("Disposing resource and calling the Close() method...");
            closed = true;
            Close();
        }
    }
}
 
public class AnotherTypeOfResource : Resource
{
    protected override void Close()
    {
        Console.WriteLine("Another type of resource closer called!");
    }
}
 
public class VirtualMethodDemo
{
    public static void Main()
    {
        Resource res = new Resource();
        AnotherTypeOfResource res2 = new AnotherTypeOfResource();
 
        res.Dispose(); // Resource.Close() will be called.
        res2.Dispose(); // even though Dispose() is part of the Resource class, 
        // the Resource class will call AnotherTypeOfResource.Close()!
    }
}

[edit] Constructors

A derived class does not automatically inherit the base class' constructors; the derived class cannot be instantiated unless it provides its own. A derived class must call one of its base class' constructors by using the base keyword:

public MyBaseClass
{
    public MyBaseClass(string text)
    {
        ...
    }
}
 
public MyDerivedClass : MyBaseClass
{
    public MyDerivedClass(int number)
        : base(number.ToString())
    { }
 
    public MyDerivedClass(string text) // even though this is exactly the same as MyBaseClass' only constructor, 
    // this is still necessary as constructors are not inherited.
        : base(text)
    { }
}

[edit] Inheritance keywords

How C# inherits from another class syntacticaly is using the ":" operator.

Example. public class Executive : Employee

To indicate a method that can be overridden, you mark the method with virtual.

public virtual void Write(string text)
{
   System.Console.WriteLine("Text:{0}", text);
}

To override a method use the override keyword

public override void Write(string  text)
{
   System.Console.WriteLine(text);
}