Java Reference
In-Depth Information
Exercise 1.6 Invoke the changeColor method, and write the color into the parameter field
without the quotes. What happens?
Pitfall A common error for beginners is to forget the double quotes when typing in a data value
of type String . If you type green instead of "green" , you will get an error message saying
something like “Error: cannot find symbol - variable green.”
Java supports several other data types, including decimal numbers and characters. We shall not
discuss all of them right now, but rather come back to this issue later. If you want to find out
about them now, look at Appendix B.
Multiple instances
Exercise 1.7 Create several circle objects on the object bench. You can do so by select-
ing new Circle() from the pop-up menu of the Circle class. Make them visible, then
move them around on the screen using the “move” methods. Make one big and yellow; make
another one small and green. Try the other shapes too: create a few triangles, squares, and
persons. Change their positions, sizes, and colors.
Once you have a class, you can create as many objects (or instances) of that class as you
like. From the class Circle , you can create many circles. From Square , you can create
many squares.
instances . Many
similar objects can
be created from a
single class.
Every one of those objects has its own position, color, and size. You change an attribute of an
object (such as its size) by calling a method on that object. This will affect this particular object,
but not others.
You may also notice an additional detail about parameters. Have a look at the changeSize
method of the triangle. Its signature is
void changeSize(int newHeight, int newWidth)
Here is an example of a method with more than one parameter. This method has two, and a
comma separates them in the signature. Methods can, in fact, have any number of parameters.
The set of values of all attributes defining an object (such as x -position, y -position, color,
diameter, and visibility status for a circle) is also referred to as the object's state. This is
another example of common terminology that we shall use from now on.
Objects have state.
The state is repre-
sented by storing
values in fields.
In BlueJ, the state of an object can be inspected by selecting the Inspect function from the ob-
ject's pop-up menu. When an object is inspected, an object inspector is displayed . The object
inspector is an enlarged view of the object that shows the attributes stored inside it (Figure 1.6).
Search WWH ::

Custom Search