Java Reference
In-Depth Information
same. Similarly, the value of
count
for both objects is the same. Note that the statement
in Line 14 only changes the value of the instance variable
x
of
illusObject2
because
x
is not a
static
member of the
class
Illustrate
.
Here are some additional comments on
static
members of a class. As you have seen
in this section, a
static
method of a class does not need any object to be invoked.
It can be called using the name of the class and the dot operator. Therefore, a
static
method cannot use anything that depends on a calling object. In other words,
in the definition of a
static
method, you cannot use a non-
static
data member or
a non-
static
method, unless there is a locally declared object that accesses the
non-
static
data member or the non-
static
method.
Finalizers
Like constructors, finalizers are also special types of methods. However, a finalizer is a
void
method. A
class
can have only one finalizer, and the finalizer cannot have any
parameters. The name of the finalizer is
finalize
. The method
finalize
automatically
executes when the class object goes out of scope. A typical use of a finalizer is to free up
the memory allocated by the object of a class.
8
Earlier in this chapter, we defined the terms mutator method and accessor method. This
section discusses these terms in detail and explains why such methods are needed to
construct a class.
Let us look at the methods of the
class
Clock
. The method
setTime
sets the values
of the data members to the values specified by the user. In other words, it alters or
modifies the values of the instance variables. Similarly, the methods
incrementHours
,
incrementMinutes
,and
incrementSeconds
also modify the instance variables. How-
ever, methods such as
getHours
,
getMinutes
,
getSeconds
,
printTime
,and
equals
only access the values of the data members; they do not modify the data members. We can,
therefore, divide the methods of the
class
Clock
into two categories: methods that
modify the data members, and methods that access, but do not modify, the data members.
This is typically true for any class. That is, almost every class has methods that only access
and do not modify the data members, called accessor methods, and methods that
modify the data members, called mutator methods.
Accessor Method:
A method of a class that only accesses (that is, does not modify) the
value(s) of the data member(s).
Mutator Method:
A method of a class that modifies the value(s) of one or more data
member(s).
Search WWH ::
Custom Search