Translate

Thursday 26 June 2014

Runtime Polymorphism and Method hiding

Runtime polymorphism:

By runtime polymorphism we can point to any derived class from the object of the base class at runtime that shows the ability of runtime binding.



namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class shape
        {
            public int _radius = 5;
            public virtual double getArea()
            {
                return 0;
            }
        }
        public class circle : shape
        {
            public override double getArea()
            {
                return 3.14 * _radius * _radius;
            }
        }
        public class sphere : shape
        {
            public override double getArea()
            {
                return 4 * 3.14 * _radius * _radius;
            }
        }
        static void Main(string[] args)
        {
            shape objBaseRefToDerived = new circle();  // run time polymorphism
            objBaseRefToDerived.getArea();

            shape objBaseRefToDerived1 = new sphere();  // run time polymorphism
            objBaseRefToDerived1.getArea();

            Console.ReadLine();
        }
    }
}

we want calculate area of circle, at the time we have to create object like

BaseclassName obj=derivedclassName()  

--------------------------------------------------------------------------------------------------
Method Hiding:

namespace PolymorphismByManishAgrahari
{
    class Program
    {
        public class Base
        {

            public virtual void Show()
            {
                Console.WriteLine("Show From Base Class.");
            }
        }

        public class Derived : Base
        {

            public new void Show()
            {
                Console.WriteLine("Show From Derived Class.");
            }
        }
        static void Main(string[] args)
        {
            Base objBaseRefToDerived = new Derived();
            objBaseRefToDerived.Show();//Output--> Show From Base Class.

            Console.ReadLine();
        }
    }
}

Output is:? Show From Base Class.

No comments:

Post a Comment