Today, I will demonstrate you about Abstract class. It is a special type of class which cannot be instantiated and it behaves as parent class for other classes. The members of abstract class marked as abstract must be implemented by derived classes. Abstract class also contains concrete member methods.
Basically we create an abstract class because of it provides basic or default functionality as well as common functionality that multiple derived classes can share and override.
Let takes an example; a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.
using System;
namespace ProgramCall
{
//Abstract class
abstract class Shape1
{
protected float R, L, B;
//Abstract methods can have only declarations
public abstract float Area();
public abstract float Circumference();
}
class Rectangle1 : Shape1
{
public void GetLB()
{
Console.Write("Enter Length : ");
L = float.Parse(Console.ReadLine());
Console.Write("Enter Breadth : ");
B = float.Parse(Console.ReadLine());
}
public override float Area()
{
return L * B;
}
public override float Circumference()
{
return 2 * (L + B);
}
}
class Circle1 : Shape1
{
public void GetRadius()
{
Console.Write("Enter Radius : ");
R = float.Parse(Console.ReadLine());
}
public override float Area()
{
return 3.14F * R * R;
}
public override float Circumference()
{
return 2 * 3.14F * R;
}
}
class MainClass
{
public static void Calculate(Shape1 S)
{
Console.WriteLine("Area : {0}", S.Area());
Console.WriteLine("Circumference : {0}", S.Circumference());
}
static void Main()
{
Rectangle1 R = new Rectangle1();
R.GetLB();
Calculate(R);
Console.WriteLine();
Circle1 C = new Circle1();
C.GetRadius();
Calculate(C);
Console.Read();
}
}
}
Abstract class has following features:
An abstract class cannot be instantiated. It means we cannot create object of that class.
It contains abstract members as well as non-abstract members [Concrete Member].
It cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
We can inherit it from a class and one or more interfaces.
It can have access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.
It can have instance variables (like constants and fields).
It can have constructors and destructors.
So, today I explain you what is abstract class and its feature.
Hope you enjoy it.