Tuesday, March 16, 2010

Abstract Classes and Methods

The purpose of an abstract class is to be inherited by other classes. It cannot be instantiated. The abstract method is, by default, a virtual method. It can exist only inside an abstract class.
Declare abstract classes or abstract methods using the abstract keyword as in this example:
abstract class MyBaseClass            //abstract class
{
    public abstract void MyMethod();  //abstract method
}
The abstract class might contain abstract methods and properties. When an abstract class is inherited, the derived class must implement all of its methods and properties. As we can see in the code segment above, the abstract method doesn’t contain any implementation. The implementation goes inside the overriding methods of the derived classes.
The following keywords are not allowed in the abstract method declaration:
•    static
•    virtual
Abstract properties are similar to abstract methods except in the way they are declared. The following example demonstrates abstract classes, methods, and properties.
//Example 2-2.cs
//Abstract classes, methods, and properties
using System;
//Abstract class:
abstract class MyBaseClass
{
    //Fields:
    protected int number = 100;
    protected string name = “Dale Sanders”;
    // Abstract method:
    public abstract void MyMethod();
    //Abstract properties:
    public abstract int Number
    { get; }
    public abstract string Name
    { get; }
}
// Inheriting the class:
class MyDerivedClass : MyBaseClass
{
    //Overriding properties:
    public override int Number
    {
        get { return number; }
    }
    public override string Name
    {
        get { return name; }
    }
    // Overriding the method:
    public override void MyMethod()
    {
        Console.WriteLine(“Number = {0}”, Number);
        Console.WriteLine(“Name = {0}”, Name);
    }
}
class MainClass
{
    public static void Main()
    {
        MyDerivedClass myObject = new MyDerivedClass();
        myObject.MyMethod();
    }
}
Note: - We now know that the override methods can override other override methods. That means that we can add another override method named MyMethod to a new class derived from MyDerivedClass. For example:
class MySecondDerivedClass : MyDerivedClass
{
    public override void MyMethod()
    {
        //Method implementation.
    }
}

No comments:

Post a Comment