Object Bench and Method Invocation

This tutorial comes with two classes supplied: Cat and CatView. Classes are represented by the yellow-ish boxes in the main window: for example, click on this link to highlight the Cat class. (Clicking on any such link in this tutorial will highlight the item on screen that they refer to.)

We will return to compilation later, but to begin with, click the Compile button in the main window to make sure our classes are compiled and ready to use.

Creating an object from a class

Let's create an instance of one of our classes: the Cat class. To create an instance, right-click on the Cat class. (If you are on Mac and don't have a right click, hold control and click whenever this tutorial says to right-click.) Then select the new Cat() option from the menu. A dialog will appear asking for a name for the object. This name is unrelated to the Java code; it is just a name that BlueJ will use to distinguish one object from another. Leave it as cat1, and click OK.

Invoking an object's methods

You should now have a red cat1 object in the bottom part of the BlueJ window that we call the object bench. The cat gets a random name and color, which you can find out by right-clicking on the red cat1 object and selecting String getDescription(). This will show a pop-up with details of the cat. (You may need to resize the window to be a bit wider to see it all.)

You can change the color of the cat using the setColor method. To invoke this, right-click on the cat1 object and select void setColor(String color). A dialog will appear asking for the method's parameter. You must use double-quotes around the value because it is a string: enter "black and white" for example, and click OK. If you then call getDescription() again, you will see that the description will change.

View an object's state

You can see the internal details of the cat object by right-clicking on the object and selecting Inspect. This shows a window with the fields of the object and their values. The cat object is fairly straightforward, it has a field containing the name, one containing the color, and another showing if it's been fed.

Part 2