There are so many combinations of return types and parameters to explore. We can’t show them all, but let’s look at a few more examples.
We haven’t explored void
methods yet. These types of methods are used when the method body doesn’t have a meaningful result to return. We commonly see this with methods that set member variables.
Take startYear
for example. Let’s make it accessible to other classes without changing the private set property. We can achieve this with a new method called setStartYear
:
public class Employee { String firstName; String lastName; public Integer startYear {get; private set;} Employee(String firstName, String lastName, Integer startYear){ this.firstName = firstName; this.lastName = lastName; this.startYear = startYear; } public Integer calculateTenure(Integer currentYear){ Integer tenure = currentYear - this.startYear; return tenure; } public void setStartYear(Integer newStartYear){ // Logic to validate startYear could go here this.startYear = newStartYear; } }
When setStartYear
runs, it will override the startYear
member variable that was originally set by the constructor. There’s no need for this method to send data back to its caller, so we’ve declared the return type as void
and omitted thereturn
statement.
Next, let’s create a method that can retrieve the full name of an employee by concatenating the first name and last name. Remember, we can concatenate two Strings together using the +
operator.
public class Employee { String firstName; String lastName; public Integer startYear {get; private set;} Employee(String firstName, String lastName, Integer startYear){ this.firstName = firstName; this.lastName = lastName; this.startYear = startYear; } public Integer calculateTenure(Integer currentYear){ return currentYear - this.startYear; // rewrote this for brevity } public void setStartYear(Integer newStartYear){ this.startYear = newStartYear; } public String getFullName(){ return this.firstName + ' ' + this.lastName; // Retrieve the member variables, concatenate them, then return the results } }
The caller will look like this:
public class EmployeeController { Integer newStartYear = 2020; Employee emp = new Employee('Elaine', 'Benes', 2019); Integer empTenure = emp.calculateTenure(2023); // Pass in 2023 as a literal. Evaluates to 4 emp.setStartYear(newStartYear); // Can also pass in as a variable empTenure = emp.calculateYearsOfEmployment(2023); // Re-evaluates to 3 String fullName = emp.getFullName(); //Evaluates to ‘Elaine Benes’ }