method overloading vs method overriding(Method hiding)

Method Overloading means having two or more methods with the same name but with different signature(deifferent parameters list and different type of paramerts) in same class or in differenet classes.
Method Overloading forms compile-time polymorphism.

example :

   class Overloading
   {
      void hello()
      { Console.WriteLine(“Hello”); }
 
      void hello(string s)
     { Console.WriteLine(“Hello {0}”,s); }
   }

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
  {
    virtual void hello()
    { Console.WriteLine(“Base Class”); }
  }

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

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

Home

No comments:

Post a Comment