Card 02/ 08

ExampleDifficulty: Intermediate1 min

equals Example: Two Identical Orders That Are Not Equal

Every field matches, the assertion fails, and a String comparison on the same line succeeds.

A class that does not override equals compares objects by identity, so two objects with identical fields are not equal. A test that builds the expected order and compares it with the one under test:

java
class Order {
    final String reference;
    final long pence;

    Order(String reference, long pence) {
        this.reference = reference;
        this.pence = pence;
    }
}
java
Order expected = new Order("AB-1", 1999);
Order actual   = new Order("AB-1", 1999);

System.out.println(expected.equals(actual));
System.out.println(expected.reference.equals(actual.reference));
text
false
true

The second line is true because String overrides equals to compare characters. The first is false because Order overrides nothing, so it inherits the default, which compares addresses, and these are two objects.

Notice that the two lines use the same method name and get their answers from two different classes. Whether equals compares contents is decided entirely by the class of the thing on the left.