Overloading
In the previous part, we have already used overloading in class Person
as it had three constructors. That's a simple example. Overloading is a feature that allows a class to have more than one method with the same name. By means of this, we can handle different situations and won't be confused. Typically, there are three ways to achieve overloading:
- Different number of parameters
- Different types of parameters
- Different order of different types of parameters
Example:
Write the following code in the /home/labex/project/overloadingTest.java
file:
public class overloadingTest{
public static void main(String[] args){
overloadingTest test = new overloadingTest();
System.out.println("add(10,20)= " + test.add(10,20));
System.out.println("add(10,20,30)= " + test.add(10,20,30));
System.out.println("add(5.5, 10.5)= " + test.add(5.5f, 10.5f));
test.printInfo(1 , "an error!");
test.printInfo("another error!" , 2);
}
// this method has two int params, returns an integer
int add(int a, int b){
return a+b;
}
// this method has three int params, returns an integer
int add(int a, int b, int c){
return a+b+c;
}
// this method has two float params, returns a float number
float add(float a, float b){
return a+b;
}
// this method has one string param and one int param, returns nothing
void printInfo(String str, int code){
System.out.println("Code: " + code + "\nMessage: " + str);
}
// this method has one int param and one string param, returns nothing
void printInfo(int code, String str){
System.out.println("Code: " + code + "\nMessage: " + str);
}
}
Output:
Run the overloadingTest.java
file using the following commands:
javac /home/labex/project/overloadingTest.java
java overloadingTest
See the output:
add(10,20)= 30
add(10,20,30)= 60
add(5.5, 10.5)= 16.0
Code: 1
Message: an error!
Code: 2
Message: another error!