The blog has moved to the new site F10Debug.com

Thursday, March 31, 2016

When to use Method Overriding & Method Hiding using real time example

When to use Method Overriding & Method Hiding using real time example

When to Use:

When we want different implementation in all derived classes and base class with default implementation, so if any derived class does not have there own implementation then default base class method will be called.

namespace OverridingExample
{
   //Base Class
   class Shape
    {
        //Method to be overridden in derive class
        public virtual void CalculateArea()
        {
               //Default Implemention.
            Console.WriteLine(" Default Area Calculated.");
        }
    }
    
    //Child Class
    class CircleShape
    {
        public override void CalculateArea()
        {
            Console.WriteLine("Circle Area Calculated.");
        }
    }
    

   class RectangleShape
    {
        public override void CalculateArea()
        {
            Console.WriteLine("Rectangle Area Calculated");
        }
    }
   

   //Class Square does not override method CalculateaArea
    class Square Shape
    {
        
    }

    class Program
    {
        static void Main(string[] args)
        {
           // Creating Object of circle class
            Shape shape1 = new Circle(); 
            shape1. CalculateArea();

            // Creating Object of rectangle class
            Shape shape2 = new Ractangel();
            shape2. CalculateArea();

            // Creating Object of Square class -> Square class does not have override method, so it will take default                     implementation of Base class
            Shape shape3 = new Square();
            shape3.CalculateArea();

            Console.ReadLine();
        }
    }
}


No comments:

Post a Comment