Java Reference
In-Depth Information
basic methods
3.4
Some methods are common to all classes. This section discusses mutators ,
accessors , and three special methods: the constructors, toString , and equals .
Also discussed is main .
3.4.1 constructors
As mentioned earlier, a basic property of objects is that they can be defined,
possibly with initialization. In Java, the method that controls how an object is
created and initialized is the constructor . Because of overloading, a class may
define multiple constructors.
A constructor tells
how an object is
declared and
initialized.
If no constructor is provided, as in the case for the IntCell class in
Figure 3.1, a default constructor is generated that initializes each data mem-
ber using the normal defaults. This means that primitive fields are initialized
to zero and reference fields are initialized to the null reference. (These defaults
can be replaced by inline field initialization, which is executed prior to exe-
cution of constructor bodies.) Thus, in the case of IntCell , the storedValue
component is 0.
To write a constructor, we provide a method that has the same name as the
class and no return type (it is crucial that the return type is omitted; a common
error is placing void as a return type, resulting in the declaration of a method
that is not a constructor). In Figure 3.6, there are two constructors: one begins
at line 7 and the other at line 15. Using these constructors, we can construct
Date objects in either of the following ways:
The default con-
structor is a mem-
ber-by-member
application of a
default initialization.
Date d1 = new Date( );
Date d2 = new Date( 4, 15, 2010 );
Note that once a constructor is written, a default zero-parameter construc-
tor is no longer generated. If you want one, you have to write it. Thus the con-
structor at line 7 is required in order to allow construction of the object that d1
references.
3.4.2 mutators and accessors
Class fields are typically declared private . Thus they cannot be directly
accessed by nonclass routines. Sometimes, however, we would like to
examine the value of a field. We may even want to change it.
One alternative for doing this is to declare the fields public . This is
typically a poor choice, however, because it violates information-hiding-
principles. Instead, we can provide methods to examine and change each
field. A method that examines but does not change the state of an object is
A method that
examines but does
not change the
state of an object
is an accessor . A
method that
changes the state
is a mutator .
 
 
Search WWH ::




Custom Search