Method Overloading In Java
By AmarSivas | | Updated : 2021-11-07 | Viewed : 219 times

Table of Contents:
Method Overloading In Java
When two or more methods have the same name with different types of parameters then that method is called method overloading.
For instance run() method as given below with different parameters.
public void run(String brand) {
System.out.println("Car's brand: "+brand);
}
public void run(String brand, String fuel) {
System.out.println("Car's brand: "+brand+" Fuel: "+fuel);
}
So here we have method run() with two different types of parameters. So these methods are called as overloaded.
Method Overloading With Changing Argument's Data Type
We will now test method overloading with changing argument data types. Here we two methods with different types of data types.
public void run(String brand, String fuel) {
System.out.println("Car's brand: "+brand+" Fuel: "+fuel);
}
public void run(int engineCapacity,long power) {
System.out.println("Car's engine capacity in CC: "+engineCapacity +" power in bhp: "+ power);
}
Here we have two run() methods with different argument data types. Overloaded methods will be invoked with respect to the parameter data types.
Method Overloading With Number Of Arguments
The method can be overloaded with a different number of arguments. So we will now see with an example.
public void run() {
System.out.println("Car is running ");
}
public void run(String brand) {
System.out.println("Car's brand: "+brand);
}
public void run(String brand, String fuel) {
System.out.println("Car's brand: "+brand+" Fuel: "+fuel);
}
/*public void run(int engineCapacity,int power) {
System.out.println("Car's engine capacity in CC: "+engineCapacity +"power in bhp: "+ power);
}*/
public void run(String brand, String fuel,int engineCapacity) {
System.out.println("Car's brand: "+brand+" Fuel: "+fuel+" engine capacity in CC: "+engineCapacity);
}
Now we can call the specific method by passing a specific number of arguments.
Method Overloading With Type Promotion
Overloading methods parameter type promotion is allowed in java. We will now look at this with an example. Consider the below-given method with two argument parameters.
public void run(int engineCapacity,long power) {
System.out.println("Car's engine capacity in CC: "+engineCapacity +" power in bhp: "+ power);
}
car.run(1197,83);
Notice we called with the method with parameter types int. But When there is no exact method match found then promotion is allowed. So now run( int, long) method will be invoked and executed. This is called method promotion.