2.1.4 How to Define an Object Parameter

Passing objects into methods is a staple of object-oriented programming and is one of the main driving forces behind re-usability and dynamic code.

Defining object parameters is the same as defining primitive values except the type will be a custom type.


In the Steal method in the employee class, there is currently nothing to actually steal.

But Sam wants to steal an entire food object and make it his own. To do this we need to make it so that Sam has access to the Food object that has been created in the MainWindow.


The first thing we need to do is define a parameter in the StealItem method of type Food.

This will cause an error in the MainWindow where the StealItem method is called because the Steal method now requires a type of Food to be passed in, but no argument has been passed in.

The object in question (the Cheetah Chips) is available to us as an object in the MainWindow.

So we can take that object and pass it into the StealItem method.

If we run the application and look at the food parameter in the StealItem method, we can expand the object in the Autos window and we can see that the food parameter is the same as (it has the same values as) the Food object instantiated in the MainWindow.

Now that the food object is available to us in the StealItem we can do things with it. Since Sam wants the food to be his own we can assign the Food field to the food parameter.

If we execute the code in the StealItem method, we can see that Sam now has the food item passed in to the method as his own Food.