C# Runtime Polymorphism by Virtual Methods

Program


using System;

namespace Polymorphism
{
    class MethodOverridingAndHieInheritance
    {
        class Shape
        {
            protected int width, height;

            public Shape(int a = 0, int b = 0)
            {
                width = a;
                height = b;
            }

            public virtual int area()
            {
                Console.WriteLine("Parent class code");
                return 0;
            }
        }

        class Rectangle : Shape
        {
            public Rectangle(int a = 0, int b = 0) : base(a, b)
            {
            }
            public override int area() //Method Overriding...
            {
                return (width * height);
            }
        }

        class Triangle: Shape
        {
            public Triangle(int a = 0, int b = 0) : base(a, b)
            {
            }
            public override int area() //Method Overriding...
            {
                return (width * height / 2);
            }
        }

        static void Main(string[] args)
        {
            Shape xShape;

            xShape = new Rectangle(10, 5);
            Console.WriteLine("Area of Rectangle: {0}",xShape.area());

            xShape = new Triangle(10, 5);
            Console.WriteLine("\nArea of Triangle:{0}",xShape.area());

            Console.ReadKey();
        }
    }
}

Output

Area of Rectangle: 50


Area of Triangle:25



No comments:

Post a Comment