method overloading in java

Method overloading is one of the most important feature of the java programming language. One method of achieving  polymorphism in java through method overloading.


Definition:
Multiple occurrence of a method / function in a class with difference in parameter type and (or) difference in  number of parameters is called method / function overloading. 

Consider the following example

      class OverloadTest  
{
int a;
String b;
public void getValues()
{
a = 10;
b = "no arguments";
}
public void getValues(int a)
{
this.a = a;
b = "with integer arguments";
}
public void getValues(String b)
{
a = 20;
this.b = b;
}
public void display()
{
System.out.println(b);
System.out.println("Value of a ="+a);
}
}
public class OverLoadDemo
{
public static void main(String args[])
{
OverloadTest test1 = new OverloadTest();
test1.getValues();
test1.display();
OverloadTest test2 = new OverloadTest();
test2.getValues(20);
test2.display();
OverloadTest test3 = new OverloadTest();
test3.getValues("with string argument");
test3.display();
}
}

In the example you can see that the method getValues() overloaded three times. First one is without any parameter, second one with an integer parameter and the final one with a String parameter. Whenever we invoke that method the compiler will find out the appropriate matching method definition and execute it. Here we invoke the three method definition with the following method calls

 test1.getValues();  
test2.getValues(20);
test3.getValues("with string argument");

Watch Video Tutorial of this Topic

Go To Tutorial Index