Friday, February 10, 2023

How method overriding different from overloading?

Overriding different from Overloading:

If we are overriding the method, derived class method behaviour is changed from the base class. In Overloading, method with same name by different signature is used.

Example:



      
      public class ParentClass
      {
            public virtual void Display()
            {
                Console.WriteLine("ParentClass");
            }
        }

        public class ChildClass : ParentClass
        {
            //Example for method override
            public override void Display()
            {
                Console.WriteLine("ChildClass");
            }

            //Example for method overload
            public void Display(string name)
            {
                Console.WriteLine(name);
            }
            //Example for method overload
            public void Display(string name, string country)
            {
            Console.WriteLine("Name:"+name +"Country: "+ country );
            }
        }


ParentClass p = new ParentClass();
ChildClass c = new ChildClass();
ParentClass pc = new ChildClass();
p.Display();
c.Display();
pc.Display();
OutPut:
ParentClass
ChildClass
ChildClass




No comments:

Post a Comment