Java Reference
In-Depth Information
this.y = y;
}
The
move
method uses
this
to clarify which
x
and
y
are being referred
to. Naming the parameters
x
and
y
is reasonable, because you pass
x
and
y
coordinates to the method. But then those parameters have the
same names as the fields, and therefore the parameter names
hide
the
field names. If we simply wrote
x= x
we would assign the value of the
x
parameter to itself, not to the
x
field as required. The expression
this.x
refers to the object's
x
field, not the
x
parameter of
move
.
Exercise 1.8
: Add a method to the
Point
class that sets the current ob-
ject's coordinates to those of a passed in
Point
object.
1.8.3. Static or Class Methods
Just as you can have per-class static fields, you can also have per-class
static methods, often known as
class methods.
Class methods are usu-
ally intended to do operations specific to the class itself, usually on static
fields and not on specific instances of that class. Class methods are de-
clared using the
static
keyword and are therefore also known as
static
methods.
As with the term "field", the word "method" generally means a per-ob-
ject method, although the term
non-static method
is sometimes used
for clarity.
Why would you need static methods? Consider the Sony Walkman fact-
ory again. The record of the next serial number to be assigned is held in
the factory, not in every Walkman. A method that returned the factory's
copy of the next available serial number would be a static method, not
a method to operate on specific Walkman objects.
The implementation of
distance
in the previous example uses the static
method
Math.sqrt
to calculate a square root. The
Math
class supports
many methods that are useful for general mathematical manipulation.