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

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

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

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
Java method overloading

Download Code

[sociallocker]method overloading[/sociallocker]

By coderss

Leave a Reply

Your email address will not be published. Required fields are marked *