Understanding C Sharp Abstract Classes

From Techotopia
Revision as of 16:58, 22 January 2008 by Neil (Talk | contribs) (Deriving from an Abstract Class)

Jump to: navigation, search

In the preceding chapters we looked in detail at object oriented programming in C# and and also at the concept of class inheritance. In this chapter we will look at the next area of object oriented programming, the abstract class.


Contents


What is a C# Abstract Class?

In the examples we have looked at so far in this book we have created classes which could be both instantiated as objects and used as a base class from which to inherit to create a subclass. Often a base class is not intended to be instantiated and is provided solely for the purpose of providing an outline for subclasses. Such a class is known as an abstract class. An abstract class cannot be instantiated as an object and is only provided for the purpose of deriving subclasses.

Abstract Members

A C# abstract class contains abstract members which define what a subclass should contain. These abstract members only declare that a member of a particular type is required, it does not implement the member. Implementation of abstract members takes place within the derived class. A subclass which derives from an abstract class and fails to implement abstract methods will fail to compile.


Declaring a C# Abstract Class

Abstract classes are declared using the abstract modifier in the class declaration:

public abstract class Hello
{
}

Abstract member functions and properties are also declared using the abstract keyword. For example to declare an abstract method in our BankAccount class the following code is required:

     public abstract void sayHello();

We now have an abstract class with an abstract method named sayHello(). Note that this declaration only states that any class derived from the Hello base class must implement a method called sayHello() which returns no value (i.e it is declared as void). It does not, however, implement the method.

Deriving from an Abstract Class

In order to subclass from an abstract class we simply write code as follows:

public class SayHello : Talk
{
}

We now have a class called SayHello which is derived from the abstract Talk class. The next step is to implement the abstract speak() method. When implementing abstract members in a derived class the override modifier must be used. For example:

public override void speak()
{
	Console.WriteLine("Hello!");
}

We now have a subclass derived from the Talk abstract class which implments the abstract speak() method.

We can now bring all of this together into a simple program:

using System;

class Hello
{


public abstract class Talk
{
	public abstract void speak();

}

public class SayHello : Talk
{
	public override void speak()
	{
		Console.WriteLine("Hello!");
	}
}

        static void Main()
        {
		SayHello hello = new SayHello();
		
		hello.speak();
        }
}