Software & Finance





C# - Virtual Functions





 

C# makes virtual functions definition perfect and it requires the use of virtual and override keywords. You need to use virual keyword in base class and override keyword in derived classes.

 

When writing derived classes C++ and C# uses ":" between derived class and base class. Java uses extends keyword instead of :

 

There are 3 classes given on this example. Shape is a base class and Circle and Triangle are the classes derived from the base class Shape. The base class Shape* is used to access all two dervied class functions.

 

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

 

namespace Polymorphism

{

 

    class Shape

    {

 

        public Shape()

        {

            System.Console.WriteLine("Shape");

        }

 

        public virtual void draw()

        {

            System.Console.WriteLine("Drawing Shape");

        }

    }

 

 

    class Circle : Shape

    {

        int r;

 

        public Circle()

        {

            System.Console.WriteLine("Circle");

        }

 

        public override void draw()

        {

            System.Console.WriteLine("Drawing Circle");

        }

    }

 

 

 

    class Triangle : Shape

    {

        public int a,b,c;

 

        public Triangle()

        {

            System.Console.WriteLine("Triangle");

        }

 

        public override void draw()

        {

            System.Console.WriteLine("Drawing Triangle");

        }

    }

 

    class InheritanceSample

    {

        static void Main()

        {

            Shape [] objects = { new Shape(),

                            new Circle(),

                            new Triangle()

            };

 

            System.Console.WriteLine("\n\nNow Drawing Objects\n");

 

            for(int i = 0; i < 3; i++)

                objects[i].draw(); // This line explains the concept of polymorphism

 

            System.Console.WriteLine("\n");

        }

    }

}

Output


Shape

Shape

Circle

Shape

Triangle

 

 

Now Drawing Objects

 

Drawing Shape

Drawing Circle

Drawing Triangle

 

Press any key to continue . . .