Java Reference
In-Depth Information
46
S ELF C HECK
16. How do you construct a square with center (100, 100) and side length 20?
17. What does the following statement print?
System.out.println(new Rectangle().getWidth());
C OMMON E RROR 2.1: Trying to Invoke a Constructor
Like a Method
Constructors are not methods. You can only use a constructor with the new
operator, not to reinitialize an existing object:
box.Rectangle(20, 35, 20, 30); // Errorȋcan't reinitialize
object
The remedy is simple: Make a new object and overwrite the current one.
box = new Rectangle(20, 35, 20, 30); // OK
2.7 Accessor and Mutator Methods
In this section we introduce a useful terminology for the methods of a class. A method
that accesses an object and returns some information about it, without changing the
object, is called an accessor method. In contrast, a method whose purpose is to modify
the state of an object is called a mutator method.
An accessor method does not change the state of its implicit parameter. A mutator
method changes the state.
For example, the length method of the String class is an accessor method. It
returns information about a string, namely its length. But it doesn't modify the string at
all when counting the characters.
The Rectangle class has a number of accessor methods. The getX, getY,
getWidth , and getHeight methods return the x- and y-coordinates of the top-left
corner, the width, and the height values. For example,
Search WWH ::




Custom Search