Card 01/ 08

ConceptDifficulty: Intermediate1 min

equals, hashCode and toString: The Methods Every Object Inherits

You print an object and get Order@2a139a55; you compare two identical ones and get false.

Every Java class extends Object, and inherits three methods from it: equals, hashCode and toString. By default equals is true only for the very same object, hashCode gives each object its own number, and toString prints the class name and that number. A class that needs anything else overrides them.

You print an object to check a value and get Order@2a139a55. You compare two objects you know hold the same data and get false. Neither class declares a single method that would explain it; both results come from the inherited defaults:

The three inherited methods and what each one does if you write nothing
MethodDefault behaviourWhat that means
equals(Object)this == otherEqual means the very same object, never the same contents
hashCode()A number chosen per objectTwo objects with identical fields usually get different numbers
toString()Class name, @, hash in hexadecimalOrder@2a139a55
java
Order a = new Order("AB-1", 10);
Order b = new Order("AB-1", 10);

System.out.println(a);
System.out.println(a.equals(b));
text
Order@2a139a55
false

The number after the @ means nothing to a reader and can change from one run to the next. What it tells you is that toString was never overridden.

The defaults are not wrong. They are the only answers a class called Object could give, because it has no idea which of your fields decide identity.

So the three are yours to write, and the decision to leave them alone is a decision too: it says that two of these objects are never equal, however identical their contents.