Difference between Method overriding and method hiding?

Last updated:9/24/2020 4:56:03 AM

1 Answers

Niraj Kumar Mishra
Niraj Kumar Mishra

Method Hiding

Method hiding is nothing but invoking the hidden base class method when the base class variable reference is pointing to the derived class object.This can be done by the new keyword in the derived class method implementation, in other words the derived class has the same method with the same name and signature.

Example:

namespace ConsoleApplication1
{
    class BaseClass
    {
        public virtual void Method()
        {
            Console.WriteLine('Base-Method');
        }
    }
    class DerivedClass:BaseClass
    {
        public new void Method()
        {
            Console.WriteLine('Derived-Method');
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            obj.Method();
            BaseClass obj1 = new DerivedClass();
            obj1.Method();
           
            Console.ReadKey();
        }
    }
}

OUTPUT :


Method Overriding

Method overriding is nothing but a feature by which a derived class can provide a new implementation for the base class method having the same name and signature as in a derived class.A derived class method can be overridden using the keyword override and that must be virtual or abstract in the base class.

Example:

namespace ConsoleApplication1
{
    class BaseClass
    {
        public virtual void Method()
        {
            Console.WriteLine('Base-Method');
        }
    }
    class DerivedClass:BaseClass
    {
        public override void Method()
        {
            Console.WriteLine('Derived-Method');
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            DerivedClass obj = new DerivedClass();
            obj.Method();
            BaseClass obj1 = new DerivedClass();
            obj1.Method();
           
            Console.ReadKey();
        }
    }
}
OUTPUT :

So, you can say that in Method hiding BaseClass variable points to the method of

DerivedClass object .

Answer