articles

Home / DeveloperSection / Articles / Method Overloading and Method overriding

Method Overloading and Method overriding

Niraj Kumar Mishra4351 23-Aug-2017
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:  
  classMethodOverloading
  {
      publicint sum(int m, int n)  //two int type Parameters method 
      {
          return m + n;
      }
      publicint sum(int m, int n, int o)  //three int type Parameters with same method same as above 
      {
          return m + n + o;
      }
      publicfloat 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 classnot 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:

    publicclassAccount1
    {
        publicvirtualint balance()
        {
            return 10;
        }
    }
 
    publicclassAccount2 : Account1
    {
        publicoverrideint 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.)


Updated 30-Jan-2019

Leave Comment

Comments

Liked By