how to use Abstract class and Method in c# .Net?
The purpose of abstract class is to provide default functionality to its sub classes.
When a method is declared as abstract in the base class then every derived class of that class must provide its own definition for that method.
An abstract class can also contain methods with complete implementation, besides abstract methods.
When a class contains at least one abstract method, then the class must be declared as abstract class.
It is mandatory to override abstract method in the derived class.
When a class is declared as abstract class, then it is not possible to create an instance for that class. But it can be used as a parameter in a method.
example
The following example creates three classes shape, circle and rectangle where circle and rectangle are inherited from the class shape and overrides the methods Area() and Circumference() that are declared as abstract in Shape class and as Shape class contains abstract methods it is declared as abstract class.
Code
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()); } } }Output
Enter Length : 10
Enter Breadth : 12
Area : 120
Circumference : 44
Enter Radius : 5
Area : 78.5
Circumference : 31.4
No comments
Post a Comment