Card 01/ 08

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.

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 derived per objectTwo objects with identical fields get different numbers
toString()Class name, @, hash in hexadecimalOrder@6d06d69c
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@6d06d69c
false

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.