next up previous
Next: 1.6.4 Help Methods, Packages, Up: 1.6.3 Inheritance and the Previous: 1.6.3 Inheritance and the

1.6.3.1 Overriding equals

As an example of inheritance, consider the method
public boolean equals(Object o);
which is defined in the class Object, the superclass of all Java classes. Any Java class that is defined without a designated superclass is an immediate subclass of the Object class. In the class Object, equals is defined to mean Object identity. Two object references are identical if and only if they refer to exactly the same object (produced by a particular new operation).

For some classes, identity is the appropriate definition for equality, but for many others it is not. In the built-in class String, the equals method is redefined to compare the sequences of characters in strings, so that copies of the same string are considered equal. The redefinition of equals only affects the class String and any subclasses that it might have. This selective form of method redefinition is called method overriding.


Finger Exercise Load the sample program intList into the DrJava Definitions window. Override the definition of equals for both Empty and Cons to match the definition of the equal? function in Scheme on lists of integers. The Scheme equal? function compares two lists to determine if they contain the same sequence of elements. Try evaluating a substantial set of test cases in the Interaction window of DrJava.


Exercise Load the saved program file ObjectList into the DrJava Definitions window. Override the definition of equals for both Empty and Cons to match the definition of the equal? function in Scheme. The Scheme equal? function uses the equal? method to compare elements.


next up previous
Next: 1.6.4 Help Methods, Packages, Up: 1.6.3 Inheritance and the Previous: 1.6.3 Inheritance and the
Corky Cartwright
2000-01-07