Card 02/ 08
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:
class Order {
final String reference;
final long pence;
Order(String reference, long pence) {
this.reference = reference;
this.pence = pence;
}
}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));false
trueThe 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.
← → move through sections and cards