Java Reference
In-Depth Information
Exercise 1.8 Make sure you have several objects on the object bench, and then inspect each
of them in turn. Try changing the state of an object (for example, by calling the moveLeft method)
while the object inspector is open. You should see the values in the object inspector change.
Figure 1.6
An object inspector,
showing details of an
Some methods, when called, change the state of an object. For example, moveLeft changes the
xPosition attribute. Java refers to these object attributes as fields.
What is in an object?
On inspecting different objects, you will notice that objects of the same class all have the
same fields. That is, the number, type, and names of the fields are the same, while the actual
value of a particular field in each object may be different. In contrast, objects of a different
class may have different fields. A circle, for example, has a “diameter” field, while a trian-
gle has fields for “width” and “height.”
The reason is that the number, types, and names of fields are defined in a class, not in an object.
So the class Circle defines that each circle object will have five fields, named diameter ,
xPosition , yPosition , color , and isVisible . It also defines the types for these fields.
That is, it specifies that the first three are of type int , while the color is of type String and the
isVisible flag is of type boolean . ( Boolean is a type that can represent two values: true
and false . We shall discuss it in more detail later.)
When an object of class Circle is created, the object will automatically have these fields.
The values of the fields are stored in the object. That ensures that each circle has a color, for
instance, and each can have a different color (Figure 1.7).
The story is similar for methods. Methods are defined in the class of the object. As a result, all
objects of a given class have the same methods. However, the methods are invoked on objects.
This makes it clear which object to change when, for example, a moveRight method is invoked.
Exercise 1.9 Figure 1.8 shows two different images. Choose one of these images and rec-
reate it using the shapes from the figures project. While you are doing this, write down what
you have to do to achieve this. Could it be done in different ways?
Search WWH ::

Custom Search