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 follows:
class Entry { String name; String address; String phone; /* constructor */ Entry(String n, String a, String p) { name = n; address = a; phone = p; } /* accessors */ String getName() { return name; } String getAddress() { return address; } String getPhone() { return phone; } /* other methods */ boolean match(String otherName) { return name.equals(otherName); } }
The match method is implemented in terms of 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 with exactly the same contents as the receiver String object. Hence,
returns true, whilenew Entry("Corky","DH 3104","x 6042")).match("Corky")
returns false.new Entry("Corky","DH 3104","x 6042")).match("Matthias")