The three instance methods getName, getAddress and getPhone in class Entry all simply return the value of a field from the object that received the method call.
Let us define another method for class Entry that does more
computation. Assume that we want to define an operation match
for the class Entry that takes a string argument keyName
and determines whether it matches the name field of the
specified Entry object. We could include such a method
definition within the definition of class Entry as shown in
Figure 1.2:
The match method is implemented using the equals method on the String field name. Recall that the String class is built-in to Java. The equals method from the String class takes an argument and returns true if (and only if) it is a String containing exactly the same sequence of characters as the receiver String object. Hence,
returns(new Entry("Corky","DH 3104","x 6042")) . match("Corky")
true,while
returns(new Entry("Corky","DH 3104","x 6042")) . match("Matthias")
false.
Warning The Java infix operator == can be used to compare objects as well as values of primitive types like int and double, but the results of such a comparison are problematic for most applications. On objects, the == operator returns true if (and only if) the both arguments are exactly the same object. Hence, if x is a variable of some object type T, the expression
returnsx == x
For distinct object arguments, the == operator returns false. Hence,true
returnsnew Entry("Corky","DH 3104","x 6042") == new Entry("Corky","DH 3104","x 6042")
because each occurrence of new creates a distinct object. For most Java object types including String, the == operator is not a reliable mechanism for testing equality! For example, Java does not guarantee that it creates only one copy of a String constant.false
Finger Exercise
Java Design Rule: There are only two valid uses of
the == operator: