Object and its methods

Every class in Java extends java.lang.Object, whether it says so or not. The extends clause of a class that names no superclass is Object, and every other class inherits its methods through the chain. A class of your own therefore already has a toString, an equals, a hashCode and a getClass before it has a line of its own, and the default implementations are the ones you replace.

The methods of Object

The class declares eleven methods, and reflection can list the public ones. The program asks the runtime for them, sorts the names and prints them:

import java.lang.reflect.Method; import java.util.Arrays; public class ObjectMethods { public static void main(String[] args) { Method[] methods = Object.class.getMethods(); String[] names = new String[methods.length]; for (int i = 0; i < methods.length; i++) { names[i] = methods[i].getName(); } Arrays.sort(names); for (String name : names) { System.out.println(name); } System.out.println("public methods: " + names.length); } }

javac -Xlint:all ObjectMethods.java
java ObjectMethods

equals
getClass
hashCode
notify
notifyAll
toString
wait
wait
wait
public methods: 9

Nine entries, because wait has three overloads. The two that are missing from the list are clone and finalize, which are protected and so invisible to a caller outside the class; they are still inherited.

The table of what each one is for:

toString writes the object as text. equals answers whether two references name the same value. hashCode gives a number that must agree with equals. getClass returns the runtime class. wait, notify and notifyAll coordinate threads and belong to the concurrency part. clone copies an object and is broken by design; finalize ran before a collection and was deprecated for removal in Java 18, so no new code overrides it.

toString

The default toString returns the class name, an @ and the hash code in hexadecimal, which tells a reader nothing about the value. A class that prints Point@1b6d3586 is asked to say what the point is. Here is a class with no override, and the four answers the default methods give for two objects with the same coordinates:

public class Defaults { public static void main(String[] args) { Point a = new Point(1, 2); Point b = new Point(1, 2); System.out.println(a.toString().startsWith("Point@")); System.out.println(a.getClass().getName()); System.out.println(a.equals(b)); System.out.println(a.equals(a)); System.out.println(a == b); System.out.println(a.hashCode() == b.hashCode()); } } class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; this.y = y; } }

javac -Xlint:all Defaults.java
java Defaults

true
Point
false
true
false
false

The program does not print the hash itself, because that number differs between runs; it prints what the number is for. The default equals is identity: an object is equal only to itself, so a.equals(a) is true and a.equals(b) is false although the two points hold the same numbers.

equals and hashCode

A value class overrides both, and then the two objects agree. The override of equals checks the type with a pattern (lesson 059 reads it in full), compares the fields, and hashCode builds a number from the same fields, so equal objects get equal numbers:

public class Same { public static void main(String[] args) { Point a = new Point(1, 2); Point b = new Point(1, 2); System.out.println(a); System.out.println(a.equals(b)); System.out.println(a.hashCode() == b.hashCode()); System.out.println(a.equals("1,2")); } } class Point { private final int x; private final int y; Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object other) { if (!(other instanceof Point point)) { return false; } return x == point.x && y == point.y; } @Override public int hashCode() { return 31 * x + y; } @Override public String toString() { return "(" + x + ", " + y + ")"; } }

javac -Xlint:all Same.java
java Same

(1, 2)
true
true
false

The last line is the part beginners forget: equals takes an Object, so any object can be passed, and a String is not a Point. A method that casts without checking would throw ClassCastException; the pattern check turns that into false, which is what equals must answer.

getClass

getClass returns the runtime class of an object, not the type of the variable that holds it. It is the difference between a reference and the object behind it, which is the whole subject of lesson 049:

public class Classes { public static void main(String[] args) { Shape shape = new Circle(2.0); System.out.println(shape.getClass().getSimpleName()); System.out.println(shape.getClass() == Circle.class); System.out.println(shape.getClass() == Shape.class); System.out.println(shape instanceof Circle); System.out.println(shape.getClass().getSuperclass().getSimpleName()); } } class Shape { } class Circle extends Shape { Circle(double radius) { } }

javac -Xlint:all Classes.java
java Classes

Circle
true
false
true
Shape

The variable is a Shape and the object is a Circle: getClass() answers Circle, and instanceof answers true for it and for its superclass. getClass is the strict test, instanceof the one that accepts subclasses, and a program that branches on the exact class is usually a program that should use a method instead.

What a class should override

Three rules cover almost every class. Override toString for any class whose value a person may read, because the default says nothing. Override equals and hashCode together, or neither, because a type that overrides one and not the other breaks every hash-based collection; lesson 040 shows the HashSet that loses an object for exactly that reason. Do not override clone, which copies fields shallowly and bypasses constructors, and never finalize, which is deprecated and runs at a time no code can predict.

A record does the three at once: equals, hashCode and toString are generated from its components, which is lesson 055. A class that holds a mutable value has one more duty, a defensive copy, in lesson 042.

Exercises

  1. Add a third point to Defaults.java with the same coordinates and count how many of the three are equals to each other.
  2. Give Point an equals that returns false for a String and true for a Point with the same fields, then print the result for both.
  3. Override toString in Circle and print the same object from a Shape variable.
  4. Ask an object for getClass().getInterfaces() and print how many interfaces it reports.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which class does every Java class extend?

    Answer

    java.lang.Object

    A class without an extends clause extends Object, and every other class inherits it through the chain.

  2. What does the default toString return?

    Answer

    The class name, an @ and the hash code in hexadecimal

    The default prints something like Point@1b6d3586, which says nothing about the value.

  3. What does the default equals compare?

    Answer

    Identity: an object is equal only to itself

    Object.equals is ==, so two objects with the same values are not equal until the class overrides it.

  4. What does this program print? public class Q1 { public static void main(String[] args) { Object a = "text"; System.out.println(a.getClass().getSimpleName()); System.out.println(a.getClass() == String.class); } }

    Answer

    String then true

    getClass returns the runtime class of the object, and the object is a String although the variable is an Object.

  5. What does this program print? public class Q2 { public static void main(String[] args) { A a = new A(); A b = new A(); System.out.println(a.equals(b)); System.out.println(a.equals(a)); } } class A { }

    Answer

    false then true

    The default equals is identity, so two objects are different and each is equal to itself.

  6. What does this program print? public class Q3 { public static void main(String[] args) { A a = new A(1); A b = new A(1); System.out.println(a); System.out.println(a.equals(b)); } } class A { private final int value; A(int value) { this.value = value; } @Override public String toString() { return "A(" + value + ")"; } }

    Answer

    A(1) then false

    toString is overridden and equals is not, so the objects print well and still compare by identity.

  7. What does this program print? public class Q4 { public static void main(String[] args) { A a = new A(2); System.out.println(a.equals("2")); System.out.println(a.equals(a)); } } class A { private final int value; A(int value) { this.value = value; } @Override public boolean equals(Object other) { if (!(other instanceof A a)) { return false; } return value == a.value; } }

    Answer

    false then true

    A String is not an A, so the pattern does not match and the method returns false.

  8. What does this program print? public class Q5 { public static void main(String[] args) { Number n = Integer.valueOf(7); System.out.println(n.getClass().getSimpleName()); System.out.println(n instanceof Number); } }

    Answer

    Integer then true

    The object is an Integer and it is an instance of its supertype Number.

  9. Why must equals and hashCode be overridden together?

    Answer

    Equal objects must have equal hash codes, or hash-based collections lose them

    A HashMap looks an object up by its hash code, so an object whose hashCode disagrees with equals is never found.

  10. What does getClass() == Circle.class test that instanceof Circle does not?

    Answer

    That the object is exactly a Circle, not a subclass of it

    getClass compares the exact runtime class, while instanceof accepts every subclass.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev

Banner image