How to Java programming- Method Overloading

Method Overloading is a feature that allows a class to have two or more methods having the same name but different argument lists. If we have to perform only one operation, having the same name of the methods increases the readability of the program. Method overloading is also known as Static Polymorphism.

Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int, int) for two parameters, and b (int, int, int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.

Method overloading increases the readability of the program.

There are two ways to overload the method in java
By changing number of arguments
By changing the data type

As discussed above, method overloading can be done by having a different argument list. Let’s see examples of each and every case.

 

Method Overloading by changing the no. of arguments.

When methods names are same but the number of arguments is different.

 

Method Overloading
	package  FirstPackage;

	class  DisplayOverloading{
		public void  disp(char c){
			System.out.println(c);
		}
		public  void  disp(char c, int num){
			System.out.println(c +  " "+num);
		}
	}
	public class  MyFirstClass{
		
		public  static void  main(String[] args) {
			// TODO Auto -generated method stub
			DisplayOverloading obj =  new  DisplayOverloading();
			obj.disp('a');
			obj.disp(a',10);
		}
	}

 

Output
     a
     a   10

 

Method Overloading by changing the data type of argument.

 

Method Overloading
	package  FirstPackage;

	public class  DisplayOverloading {

		void  sum(int  a,int  b){
			System.out.println(a+b);
		}
		void  sum(double  a,double  b){
			System.out.println(a+b);
		}
		public static void  main(String[] args) {
			// TODO Auto -generated method stub
			DisplayOverloading  obj.new DisplayOverloading(),
			obj.sum(10.5,10.5);
			obj.sum(20,20);
		}
	}

 

Output
    21.0
    40

 

In this example, we have created two overloaded methods that differ in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...