Method Overriding and Method Hiding [C#]


Method Overriding vs Method Hiding
Method Hiding is the concept of hiding the base class function from the derived class.We can create the complete new definition of base class function in derived class function.we can say hiding the base class function from derived class.Method Hiding can be achieved by using new keyword.
  public class Base 
        {
               public void Hello()
               {
                     

                   Console.WriteLine("Base Class");
               }
        }

        public class Derived : Base
        {
               public new void Hello()
               {

                   Console.WriteLine("Derived Class");
               }
         }
         public class TestHiding
         {

             public static void Main(string[] args)
             {

                  Derived  obj= new Derived ();                  

                  obj.Hello(); 
                  Console.ReadLine();
            }

         } 
 Output : Derived Class
 Method overriding means having two methods with same name and same siganture, one method in base class and other method in derived class.
   A subclass inherits methods from a base class. Sometimes, it is necessary for the subclass to modify the methods defined in the base class. This is referred to as method overriding.
   This can be achieved by using the virtual and override keywords. we have to use the virtual keyword for the method which in base class and override keyword  for the method in subclass.

   By default functions are not virtual in C# and so you need to write “virtual” explicitly.

   Class BaseClass
  {
    public virtual void hello()
    { Console.WriteLine(“Base Class”); }
  }

  Class SubClass : BaseClass
  {
    public override void hello()
   { Console.WriteLine(“SubClass”); }
  }

  static void main()
  {
    BaseClass objBase = new SubClass();
    objBase.hello();
  }

  //Output  ::: SubClass....

No comments:

Post a Comment