Example of how to use abstract class
In this project I have calculated area of circle and rectangle.I have created abstract class in which abstract method is created which is called in other classes to using override method.A point to be noted is this,an abstract class must contain an abstract method whose implementation is done in the class which calls it or used it.
Abstract class
is a class which must contain an abstract method whose implementation is done in derived class which uses abstract class.Though it may contain non abstract method with implementation.
In this program i have created an asbtract class named shape and inside it i have created an asbstract method named area.Now I will inherit shape class in circle and rectangle class and use abstract method area in each class by providing its implemention it separately in each class.area method in circle class claculates yhe area of circle while in rectangle class it clacultes area of rectangle.So by overriding a method with same name we can use it in different ways to calcuate different things.
abstract class shape
{
abstract public void area();
}
class circle:shape
{
public override void area()
{
Console.WriteLine("Enter radius of circle");
double r = Convert.ToDouble(Console.ReadLine());
double area;
area = 3.14*r*r;
Console.WriteLine("Area of circle is" + area);
}
}
class rectangle:shape
{
public override void area()
{
Console.WriteLine("Enter length of rectangle");
double l = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Enter breadth of rectangle");
double b = Convert.ToDouble(Console.ReadLine());
double area;
area = l*b;
Console.WriteLine("Area of rectangle is" + area);
}
}
class Program
{
static void Main(string[] args)
{
circle c = new circle();
c.area();
rectangle r = new rectangle();
r.area();
Console.ReadLine();
}
}