Virtual And Override Methods C# With Example



A virtual method is invoked, and the run-time type of the object is checked for an overriding member.
The overriding member is the most derived.

using System;

namespace CSharpInterface
{
    abstract class Shape
    {
        public double dim1, dim2;

        public Shape(double dimension1, double dimension2)
        {
            dim1 = dimension1;
            dim2 = dimension2;
        }

        abstract public double area();
    }
    class Rectangle : Shape
    {
        public Rectangle(double dimension1, double dimension2) : base(dimension1, dimension2) { }

        override public double area()
        {
            Console.WriteLine("\nInside Area for Rectangle : ");
            return dim1 * dim2;
        }
    }

    class Triangle : Shape
    {
        public Triangle(double dimension1, double dimension2) : base(dimension1, dimension2) { }

        override public double area()
        {
            Console.WriteLine("\nInside Area for Triangle : ");
            return dim1 * dim2 / 2;
        }
    }

    class AbstractClass
    {
        public static void Main(string[] args)
        {
            Rectangle newRectangle = new Rectangle(6, 7);
            Triangle newTriangle = new Triangle(12, 23);

            Shape referenceShape;

            referenceShape = newRectangle;
            Console.WriteLine("Area is " + referenceShape.area());

            referenceShape = newTriangle;
            Console.WriteLine("Area is " + referenceShape.area());
        }
    }
}

0 Comment's

Comment Form

Submit Comment