In Java, method overloading can be achieved in three main ways:
-
By Changing the Number of Parameters: You can create multiple methods with the same name but different numbers of parameters.
public class OverloadExample { void display(int a) { System.out.println("Integer: " + a); } void display(int a, String b) { System.out.println("Integer: " + a + ", String: " + b); } } -
By Changing the Type of Parameters: You can overload methods by changing the types of parameters.
public class OverloadExample { void display(int a) { System.out.println("Integer: " + a); } void display(String b) { System.out.println("String: " + b); } } -
By Changing the Order of Parameters: You can also overload methods by changing the order of parameters if they have different types.
public class OverloadExample { void display(String b, int a) { System.out.println("String: " + b + ", Integer: " + a); } void display(int a, String b) { System.out.println("Integer: " + a + ", String: " + b); } }
These methods allow you to define multiple methods with the same name but different signatures, enabling more flexible code.
