Method Overloading :

 

Method overloading is a feature of object oriented programming where you can make or create multiple method with same name but parameters and types are different in a single class. 

You can be achieve method overloading by following things:
1. By changing the number of parameters used.
2. By changing the order of parameters.
3. By using different data types for the parameters.

 

Example:  
  class MethodOverloading
  {
      public int sum(int m, int n)  //two int type Parameters method 
      {
          return m + n;
      }
      public int sum(int m, int n, int o)  //three int type Parameters with same method same as above 
      {
          return m + n + o;
      }
      public float sum(float m, float n, float o, float p) //four float type Parameters with same method same  as above
      {
          return m + n + o + p; ;
      }
  }


As you can see that in the above example we have created three methods with

same name sum() but all of them having different parameters and types.

Important Question for method overloading

Question: Can method overloading has same numbers of parameters and name


with different return types?


Answer: No, because conflict is arise in methods while passing the parameters.  

 

Method Overriding :

 

Method Overriding means if you are creating a method in a child or derived class with same name and parameters and also defining same return types as in the base class then it is called as method overriding . 

Some key points of method overriding
- Method overriding is only possible in child class or derived class not within the
same class where the method is declared.
- You can only overrides those methods in derived class that are already declared in
base class with virtual keyword or abstract keyword.
 
Example:

    public class Account1
    {
        public virtual int balance()
        {
            return 10;
        }
    }
 
    public class Account2 : Account1
    {
        public override int balance()
        {
            return 500;
        }
    }

So, we can say that, the method overriding is very useful when we want to return different output of same method in different child classes according to the need.

Note: in the above example balance() method of Account2 class having a keyword ‘override’, because if we override any method of base class without using ‘override’ keyword then it will show a warning message like this – (To make the current member override that implementation, add the override keyword. Otherwise add the new keyword.)

  Modified On Nov-30-2017 12:41:35 AM

Leave Comment