Java Object Class and the equals Method
Object is the superclass of every Java class. Learn what Object variables can hold, the difference between == and equals, how to write a correct equals method, the five rules of the equals contract, getClass vs instanceof in class hierarchies, and the classic mistakes to avoid.
kvi5hnuCode Sprout team member10 min readOn this page
Object: The Root of Every Class Hierarchy
java.lang.Object sits at the top of every hierarchy: a class that names no superclass extends Object implicitly, so there's no need to write
public class Employee extends Object
Because every object inherits Object's methods, those methods are worth knowing well. The most important are equals, hashCode and toString, covered in this and the next article. getClass comes up with reflection, clone in the interfaces part, and wait/notify in the concurrency part.
Variables of type Object
A variable of type Object can refer to an object of any type:
Object obj = new Employee("Omar Haddad", 52000);
Through an Object variable you can only call Object's own methods. To use the employee as an employee again, test and convert the reference, preferably with a pattern:
Employee e = (Employee) obj;
if (obj instanceof Employee emp) { . . . }
Everything except primitive values is an object, and that includes every array, even an int[]:
Employee[] staff = new Employee[10];
obj = staff; // OK
obj = new int[10]; // OK
(Primitive values can still be stored in Object variables through autoboxing: Object o = 42; stores an Integer. See the wrapper classes article.)
The equals Method
equals answers "should these two objects count as the same?". The version inherited from Object answers it in the strictest way: only if both references point to one and the same object (this == other).
For many classes that is exactly right. Two Thread objects or two open Scanners are different things even if they look alike. For classes that represent values or data, though, you usually want two objects with the same contents to be equal.

Writing equals for Employee
For this example, treat two Employee objects as equal when name, salary and start date all match. (A real HR system would compare a unique staff number; here the point is the technique.)
public class Employee {
. . .
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) return true; // same object: trivially equal
if (otherObject == null) return false; // nothing equals null
if (getClass() != otherObject.getClass()) return false; // different classes never match
var other = (Employee) otherObject; // safe after the class check
return name.equals(other.name)
&& Double.compare(salary, other.salary) == 0 // not ==; see the recipe below
&& startDate.equals(other.startDate);
}
}
The getClass method returns the runtime class of an object (covered with reflection later in this part). With this test, two objects can be equal only if they belong to the same class.
equals in a subclass
A subclass's equals should let the superclass compare the inherited part first, then check its own fields:
public class Manager extends Employee {
. . .
@Override
public boolean equals(Object otherObject) {
if (!super.equals(otherObject)) return false;
// super.equals checked that this and otherObject belong to the same class
var other = (Manager) otherObject;
return Double.compare(bonus, other.bonus) == 0;
}
}
The cast is safe because Employee.equals already verified that both objects have the same class.
The equals Contract
The Java API specification requires equals to be an equivalence relation:
- Reflexive: for any non-null reference
x,x.equals(x)returnstrue. - Symmetric: for any references
xandy,x.equals(y)returnstrueif and only ify.equals(x)returnstrue. - Transitive: if
x.equals(y)andy.equals(z)both returntrue, thenx.equals(z)returnstrue. - Consistent: if the objects haven't changed, repeated calls to
x.equals(y)return the same value. - Non-null: for any non-null
x,x.equals(null)returnsfalse.
Collections depend on these rules. list.contains(x) may evaluate x.equals(element) or element.equals(x), and HashSet, HashMap and friends assume the answers agree. A class that breaks the contract makes those collections give inconsistent answers.
Equality Testing and Inheritance: getClass or instanceof?
What should happen when one object is an Employee and the other a Manager? Developers disagree about this. The version above says "never equal" because it requires identical classes. The popular alternative checks with instanceof:
if (!(otherObject instanceof Employee)) return false;
Now subclass objects pass the test, and that collides with symmetry. Take an Employee e and a Manager m with the same name, salary and start date. Employee.equals with instanceof reports e.equals(m) as true. Symmetry then demands that m.equals(e) be true as well. So Manager.equals may not look at the bonus when the other object is a plain employee, which largely defeats the purpose of overriding it.

The getClass approach has its critics too: it means a subclass instance can never stand in for a superclass instance in an equality check. The JDK's collection types show the other side. List.equals is specified for all lists, so an ArrayList and a LinkedList with the same elements are equal, and likewise for sets. That works because the meaning of equality is defined once, in the interface, and no implementation is allowed to change it.
Which approach fits depends on who defines equality:
| Scenario | Use | Consequence |
|---|---|---|
Subclasses can have their own notion of equality (a Manager compares bonuses too) | the getClass test | Objects of different classes are never equal; symmetry holds |
| The notion of equality is fixed in the superclass (e.g., equality by employee ID) | the instanceof test, and make equals final | Objects of different subclasses can be equal to each other |
Here, two managers who differ only in their bonus should not be equal, so Manager needs its own rule and getClass is the right test. If equality were based on a staff number shared by all kinds of employee, the rule would belong to Employee alone: use instanceof and declare equals final.
Writing equals Step by Step
-
Declare the parameter with type
Object; any other type overloads instead of overrides (see the mistake below). Calling itotherObjectleaves the nameotherfree for the converted reference. -
Return
trueimmediately when both references are the same object:javaif (this == otherObject) return true;It isn't required for correctness, but it is cheap and skips the field comparisons.
-
Return
falsefornull. The contract demands it:javaif (otherObject == null) return false; -
Check the type. When subclasses may redefine equality, require the exact same class:
javaif (getClass() != otherObject.getClass()) return false; ClassName other = (ClassName) otherObject;When one definition covers the whole hierarchy, use an
instanceofpattern:javaif (!(otherObject instanceof ClassName other)) return false;The pattern binds
otheron success. Sinceinstanceofisfalsefornull, this form also covers step 3. -
Compare the significant fields:
==for integral primitives,Double.compare/Float.comparefor floating point (see below),Objects.equalsfor references. All must match:javareturn field1 == other.field1 && Objects.equals(field2, other.field2) && . . .;
A subclass override starts with super.equals(otherObject). And overriding equals always means overriding hashCode as well (next article).
The classic mistake: overloading instead of overriding
Can you spot the problem?
public class Employee {
public boolean equals(Employee other) {
return other != null
&& getClass() == other.getClass()
&& Objects.equals(name, other.name)
&& Double.compare(salary, other.salary) == 0
&& Objects.equals(startDate, other.startDate);
}
. . .
}
The parameter type is Employee, not Object. So this method doesn't override Object.equals: it overloads it with a completely unrelated method. It works when the compiler sees two Employee types, but collections call equals(Object) and get the inherited identity test:
oops.equals(Oops): true
oops.equals(Object): false
list.contains: false
Protect yourself with @Override:
@Override public boolean equals(Employee other) // error: method does not override or implement a method from a supertype
A Complete Example
import java.time.LocalDate;
import java.util.*;
public class Solution {
public static void main(String[] args) {
var rina1 = new Employee("Rina Sato", 64000, 2016, 4, 11);
var rina2 = rina1;
var rina3 = new Employee("Rina Sato", 64000, 2016, 4, 11);
var tomas = new Employee("Tomas Berg", 49000, 2019, 9, 2);
System.out.println("rina1 == rina2: " + (rina1 == rina2));
System.out.println("rina1 == rina3: " + (rina1 == rina3));
System.out.println("rina1.equals(rina3): " + rina1.equals(rina3));
System.out.println("rina1.equals(tomas): " + rina1.equals(tomas));
var priya = new Manager("Priya Nair", 91000, 2016, 4, 11);
var boss = new Manager("Priya Nair", 91000, 2016, 4, 11);
boss.setBonus(6500);
System.out.println("priya.equals(boss): " + priya.equals(boss));
var plainPriya = new Employee("Priya Nair", 91000, 2016, 4, 11);
System.out.println("plainPriya.equals(priya): " + plainPriya.equals(priya));
// the overloading trap
var oops = new Oops("x");
Object asObject = new Oops("x");
System.out.println("oops.equals(Oops): " + oops.equals(new Oops("x")));
System.out.println("oops.equals(Object): " + oops.equals(asObject));
System.out.println("list.contains: " + List.of(new Oops("x")).contains(new Oops("x")));
// asymmetric sets
Set<String> x = new HashSet<>(List.of("Tea", "Milk"));
Set<String> y = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
y.addAll(List.of("Tea", "MILK"));
System.out.println("x.equals(y): " + x.equals(y) + ", y.equals(x): " + y.equals(x));
// arrays
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a.equals(b) + " " + Arrays.equals(a, b));
int[][] m1 = {{1}, {2}};
int[][] m2 = {{1}, {2}};
System.out.println(Arrays.equals(m1, m2) + " " + Arrays.deepEquals(m1, m2));
// doubles
System.out.println((Double.NaN == Double.NaN) + " " + (Double.compare(Double.NaN, Double.NaN) == 0));
System.out.println((0.0 == -0.0) + " " + (Double.compare(0.0, -0.0) == 0));
// records get equals for free
record Point(int x, int y) { }
System.out.println(new Point(1, 2).equals(new Point(1, 2)));
}
}
class Employee {
private final String name;
private double salary;
private final LocalDate startDate;
public Employee(String name, double salary, int year, int month, int day) {
this.name = name;
this.salary = salary;
startDate = LocalDate.of(year, month, day);
}
@Override
public boolean equals(Object otherObject) {
if (this == otherObject) return true; // same object: trivially equal
if (otherObject == null) return false; // nothing equals null
if (getClass() != otherObject.getClass()) return false; // different classes never match
var other = (Employee) otherObject; // safe after the class check
return Objects.equals(name, other.name)
&& Double.compare(salary, other.salary) == 0
&& Objects.equals(startDate, other.startDate);
}
@Override
public int hashCode() {
return Objects.hash(name, salary, startDate);
}
}
class Manager extends Employee {
private double bonus;
public Manager(String name, double salary, int year, int month, int day) {
super(name, salary, year, month, day);
}
public void setBonus(double bonus) { this.bonus = bonus; }
@Override
public boolean equals(Object otherObject) {
if (!super.equals(otherObject)) return false;
var other = (Manager) otherObject;
// super.equals checked that this and other belong to the same class
return Double.compare(bonus, other.bonus) == 0;
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), bonus);
}
}
class Oops {
private final String id;
Oops(String id) { this.id = id; }
public boolean equals(Oops other) { // WRONG: overloads instead of overriding
return other != null && id.equals(other.id);
}
}
rina1 == rina2: true
rina1 == rina3: false
rina1.equals(rina3): true
rina1.equals(tomas): false
priya.equals(boss): false
plainPriya.equals(priya): false
oops.equals(Oops): true
oops.equals(Object): false
list.contains: false
x.equals(y): false, y.equals(x): true
false true
false true
false true
true false
true
(The hashCode methods are explained in the next article. Note that Oops breaks the contract between equals and hashCode too.)
Common questions
Do I need to override equals in every class?
No. Identity equality from Object is correct for many classes: services, threads, connections, and entities whose identity really is the object. Override it for value-like classes where two objects with the same state should count as equal. For pure data, use a record and get a correct equals for free.
Should equals use getClass() or instanceof?
Use getClass() when subclasses may add state that affects equality. Use instanceof (and make equals final) when equality is defined the same way for the whole hierarchy, for example by an ID. For a final class the two are equivalent, and the pattern form instanceof Point other is the most concise.
Is it safe to use mutable fields in equals?
It is legal, but objects stored in a HashSet or used as HashMap keys must not change those fields while they are stored. Otherwise the collection can no longer find them. Base equals on fields that don't change, or keep such objects out of hash-based collections while they are being modified.
How does equals behave with null fields?
name.equals(other.name) throws when name is null. Use Objects.equals(name, other.name), which treats two nulls as equal and doesn't throw.
Should I compare enums with equals or ==?
Both work, but == is preferred. Each enum constant exists exactly once, so identity and equality are the same thing. == is also null-safe and is checked at compile time against the enum type.
Summary
- Every class extends
Object. AnObjectvariable can hold any object, including arrays, and primitives via boxing. ==tests identity.Object.equalsdoes the same unless a class overrides it with state-based equality.equalsmust be reflexive, symmetric, transitive, consistent, and returnfalsefornull.- Use
getClasswhen subclasses define their own equality, andinstanceof(with afinalequals) when equality is fixed in the superclass. - Recipe: identity check → null check → class check and cast → field comparison (
==orDouble.comparefor primitives,Objects.equalsfor objects,Arrays.equals/deepEqualsfor arrays). Subclasses callsuper.equalsfirst. - The parameter must be
Object; always use@Override. OverridehashCodewhenever you overrideequals. Records generate both.
Practice Questions
Two different String objects contain "Java". What do s == t and s.equals(t) return?
s == t is false (different objects, unless both come from the same literal in the string pool). s.equals(t) is true, because String overrides equals to compare characters.
Write an equals method for class Point { private final int x, y; } that allows no subclass-specific equality.
@Override
public final boolean equals(Object otherObject) {
if (this == otherObject) return true;
if (!(otherObject instanceof Point other)) return false;
return x == other.x && y == other.y;
}
(Plus a matching hashCode, e.g. Objects.hash(x, y). Or simply use record Point(int x, int y).)
Employee.equals uses instanceof; Manager.equals also compares bonus. Which equals rule is broken?
Symmetry. employee.equals(manager) can be true (Employee ignores the bonus), while manager.equals(employee) is false or throws a ClassCastException. Transitivity can break too.
Why must the parameter of equals be Object and not the class type?
Only equals(Object) overrides Object.equals. With another parameter type, you create an overload, which collections never call. They use equals(Object) and get identity comparison. @Override catches the mistake.
A class has a field int[] scores. Why is Objects.equals(scores, other.scores) wrong?
For arrays, equals is identity, so two arrays with the same contents compare unequal. Use Arrays.equals(scores, other.scores) (or Arrays.deepEquals for nested arrays).
Previous: Java final Classes and Methods, Casting, instanceof Patterns and protected Access
Related reading
- Java final Classes and Methods, Casting, instanceof Patterns and protected Access
- Java Polymorphism and Dynamic Binding: How Method Calls Are Resolved
- Java Inheritance: Superclasses, Subclasses and Method Overriding
- Java Class Design Hints: Writing Clean, Maintainable Classes
- Java Package Access and the Class Path

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.