2.2.4 How to Return an Object from a Method

Returning objects is very similar to returning values. The main difference is using custom types instead of primitive types.

The ComoZoo has an opening for a Boss and they are looking to hire. We can define a method in the Employee class for when someone from HR hires a new Employee.

We could try to assign the new Employee a role, but since it's being instantiated in the Employee class, there is no access to the ComoZoo's fields.

And even if we executed the HireEmployee method nothing would happen because as soon as the method instantiates a new Employee...

...and we return to the call...

...there is no new Employee because the the Employee object's scope was limited just to that method.


What we need to do, then, is return the new Employee object from the method. To do this, we need to change the method header to return the type we want returned instead of void and add a return statement for the employee.

Then we need to make sure we don't "drop" the Employee object when the HireEmployee method is called because we would still like to use it.

Now when we run the application and step through the code, the HireEmployee method returns an Employee object and the newHire variable is assigned the object.

Now that we have access to the object and the ComoZoo is within our scope (because this call is in the MainWindow), we can assign the object values and assign it to fields.

Here we can see that the newHire and the Boss are both Serena.