An abstract method is a method without a body. The implementation of an abstract method is done by a derived class. When the derived class inherits the abstract method from the abstract class, it must override the abstract method. When you create a derived class, you must provide an override method for all abstract methods in the abstract class.
- namespace ConsoleApplication2
- {
- class Program
- {
- public static void Main()
- {
-
- ovrCalculate ovr= new ovrCalculate();
- Console.WriteLine("sum are "+ovr.Addition(3,3));
- Console.WriteLine("Multiplication are "+ovr.Multiplication(3, 3));
- Console.ReadLine();
- }
- }
-
- abstract class Calculate
- {
-
-
- public int Addition(int n1, int n2)
- {
- return n1 + n2;
-
- }
-
-
-
- public abstract int Multiplication(int n1, int n2);
-
- }
-
- class ovrCalculate : Calculate
- {
-
-
- }
So, a class derived from an abstract class contains abstract methods and those methods must be defined in the derived class otherwise it won't compile.
- class ovrCalculate : Calculate
- {
-
- public override int Multiplication(int Num1, int Num2)
- {
-
- return Num1 * Num2;
-
- }
- }
Now it compiles successfully.
And the output is:
By default, methods are non-virtual. You cannot override a non-virtual method.
You cannot use the virtual modifier with the static, abstract, private, or override modifiers. The following example shows a virtual property:
- class Program
- {
- public static void Main()
- {
- Shape ss = new Shape(2.2,2.2);
- Console.WriteLine("here shape class area method call " + ss.Area());
- Circle cc = new Circle(2.0);
- Console.WriteLine("derived class area methods call "+cc.Area());
- Console.ReadLine();
-
- }
- }
-
- public class Shape
- {
- public const double PI = Math.PI;
- protected double x, y;
- public Shape()
- {
- }
- public Shape(double x, double y)
- {
- this.x = x;
- this.y = y;
- }
-
- public virtual double Area()
- {
- return x * y;
- }
- }
-
- public class Circle : Shape
- {
- public Circle(double r)
- : base(r, 0)
- {
- }
-
- public override double Area()
- {
- return PI * x * x;
- }
- }
-
The output would be:
So here I tried to explain abstract methods and the virtual and override keywords.