Tuesday, November 18, 2008

Simple Abstract Class- Definition with Example


Abstract Class:

Abstract classes are one of the essential behaviors provided by .NET. Commonly, you would like to make classes that only represent base classes, and don’t want anyone to create objects of these class types. You can make use of abstract classes to implement such functionality in C# using the modifier 'abstract'.

An abstract class means that, no object of this class can be instantiated, but can make derivations of this.

An abstract class can contain either abstract methods or non abstract methods. Abstract members do not have any implementation in the abstract class, but the same has to be provided in its derived class.


Example :


using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication2
{

abstract class Class1
{
public void Add(int n1, int n2)
{
int n3;
n3= n1 + n2;
Console.WriteLine("N3:" + n3);
Console.ReadLine();
}
public abstract void Multiply(int x, int y);

}


class Program:Class1
{
string c;
int z;
public void Concatenate(string a, string b)
{
c = a + b;
Console.WriteLine(" C:" + c);
Console.ReadLine();
}
public static void Main(string[] args)
{
Program pgm = new Program();
pgm.Add(10, 20);
pgm.Concatenate("Hem", "nath");
pgm.Multiply(20, 100);

}
public override void Multiply(int e, int f)
{
z = e * f;
Console.WriteLine("Z:" + z);
Console.ReadLine();
}
}

}

In the above sample, you can see that the abstract class Class1 contains two methods Add and Multiply. Add is a non-abstract method which contains implementation and Multiply is an abstract method that does not contain implementation.

The class Program is derived from Class1 and the Multiply is implemented on Program. Within the Main, an instance ( pgm) of the Program is created, and calls Add and Multiply.

No comments: