Java Reference
In-Depth Information
The advantage of using a mutator is that the mutator can ensure that
changes in the state of the object are consistent. Thus a mutator that changes
the day field in a Date object can make sure that only legal dates result.
3.4.3 output and toString
Typically, we want to output the state of an object using print . This is done by
writing the class method toString . This method returns a String suitable for
output. As an example, Figure 3.6 shows a bare-bones implementation of the
toString method for the Date class.
The toString
method can be pro-
vided. It returns a
String based on
the object state.
3.4.4 equals
The equals method is used to test if two objects represent the same value. The
signature is always
The equals method
can be provided to
test if two refer-
ences are referring
to the same value.
public boolean equals( Object rhs )
Notice that the parameter is of reference type Object rather than the class
type (the reason for this is discussed in Chapter 4). Typically, the equals
method for class ClassName is implemented to return true only if rhs is an
instance of ClassName , and after the conversion to ClassName , all the primitive
fields are equal (via == ) and all the reference fields are equal (via member-by-
member application of equals ).
An example of how equals is implemented is provided in Figure 3.6 for
the Date class. The instanceof operator is discussed in Section 3.6.3.
The parameter to
equals is of type
Object .
3.4.5 main
When the java command is issued to start the interpreter, the main method in
the class file referenced by the java command is called. Thus each class can
have its own main method, without problem. This makes it easy to test the
basic functionality of individual classes. However, although functionality can
be tested, placing main in the class gives main more visibility than would be
allowed in general. Thus calls from main to nonpublic methods in the same
class will compile even though they will be illegal in a more general setting.
example: using java.math.BigInteger
3.5
Section 3.3 describes how to generate documentation from a class, and
Section 3.4 describes some typical components of a class, such as construc-
tors, accessors, mutators, and in particular equals and toString . In this
 
 
Search WWH ::




Custom Search