Card 02/ 08

ExampleDifficulty: Intermediate1 min

Two Identical Orders That Java Says Are Not Equal

A test that builds the expected order and compares it with the one under test. Every field matches and the assertion fails.

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.

What to notice: 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.