Card 01/ 08
All 8 cards
ConceptDifficulty: Intermediate1 min
The Three Methods Every Object Already Has
You print an object to check a value and get Order@6d06d69c. You compare two objects you know hold the same data and get false. Neither class declares a single method that would explain it.
Every class in Java extends Object, whether or not anybody wrote it down, and Object supplies three methods that your class inherits with default behaviour.
| Method | Default behaviour | What that means |
|---|---|---|
equals(Object) | this == other | Equal means the very same object, never the same contents |
hashCode() | A number derived per object | Two objects with identical fields get different numbers |
toString() | Class name, @, hash in hexadecimal | Order@6d06d69c |
Order a = new Order("AB-1", 10);
Order b = new Order("AB-1", 10);
System.out.println(a);
System.out.println(a.equals(b));Order@6d06d69c
falseThe 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.