Java Method overloading is something like having more than one method with the same name and different parameters but, all methods should be in the same class, if those are in different classes then it is not considered as a method overloading
You can implement Java method overloading using below ways
- Method name is same and changing data type of parameters
- Method name is same and changing no of parameters
- Method name is same and changing order of parameters
Let us take a simple example, you can get the employee information either by passing employee id or if you want to apply more filters then you can pass employee id along with the department id something like below
Example: Method name is same and changing data type of parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.keysandstrokes.examples.polymorphism; public class EmployeManager { EmployeBean bean = new EmployeBean(); public EmployeManager() { bean.setAge(29); bean.setDeptNo(10); bean.setId(100); bean.setName("author1"); } public EmployeBean getEmployeInformation(int employeeId) { return bean; } public EmployeBean getEmployeInformation(String employeeName) { return bean; } } |
Example: Method name is same and changing no of parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.keysandstrokes.examples.polymorphism; public class EmployeManager { EmployeBean bean = new EmployeBean(); public EmployeManager() { bean.setAge(29); bean.setDeptNo(10); bean.setId(100); bean.setName("author1"); } public EmployeBean getEmployeInformation(int employeeId) { return bean; } public EmployeBean getEmployeInformation(String employeeName) { return bean; } public EmployeBean getEmployeInformation(int employeeId, String deportmentId) { return bean; } } |
Example: Method name is same and changing order of parameters
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.keysandstrokes.examples.polymorphism; public class EmployeManager { EmployeBean bean = new EmployeBean(); public EmployeManager() { bean.setAge(29); bean.setDeptNo(10); bean.setId(100); bean.setName("author1"); } public EmployeBean getEmployeInformation(int employeeId) { return bean; } public EmployeBean getEmployeInformation(String employeeName) { return bean; } public EmployeBean getEmployeInformation(int employeeId, String deportmentId) { return bean; } public EmployeBean getEmployeInformation(String employeeName, int employeeId) { return bean; } public String getEmployeInformation(int employeeId, String deportmentId, String employeeName) { return "employee"; } } |
When you try to call in your consumer class you should see something like below, it listed out all getEmployeeInformation() overloaded method, the consumer can use whatever he/she wants