In the Inheritance chapter, we learned that a class can extend another class. But what about a class that doesn't extend anything, like this one?
class Student {
String name;
}Surprisingly, even this class has a parent. If a class does not extend any other class, Java automatically makes it extend java.lang.Object. So the code above is treated as:
class Student extends Object {
String name;
}This means Object is the root of every class in Java. Every object you create, whether it is a String, a StringBuilder, or your own Student, inherits a set of methods from Object.
Object
┌────────┼─────────┐
String Student Animal
│
Dog (Dog → Animal → Object)In this chapter, we will learn the most important of these methods: toString(), equals(), hashCode(), and getClass(), and how to override them correctly.
The Methods of the Object Class
Here are the methods every class inherits from Object:
Method | What it does |
|---|---|
| Returns a text representation of the object |
| Checks whether another object is "equal" to this one |
| Returns an |
| Returns the actual class of the object at runtime |
| Creates a copy of the object (only works if the class implements |
| Used for communication between threads (multithreading) |
| Old cleanup method; deprecated and should not be used |
You will override toString(), equals(), and hashCode() very often. getClass() is final, so it cannot be overridden, but it is useful to call.
The Default Behaviour
Let's see what the inherited methods do if we don't override them:
class Student {
int rollNumber;
String name;
Student(int rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Aman");
Student s2 = new Student(101, "Aman");
System.out.println(s1);
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}Output (the part after @ will be different on your computer):
Student@5acf9800
false
falseTwo surprises here:
Printing the object gives
Student@followed by a hexadecimal number. The defaulttoString()returns the class name, an@, and the object's hash code in hexadecimal. That is not very useful to a human.s1.equals(s2)isfalse, even though both students have the same roll number and name. The defaultequals()behaves exactly like==: it only returnstrueif both references point to the same object.
To get better behaviour, we override these methods.
Overriding toString()
toString() should return a readable description of the object. Java calls it automatically whenever an object is printed with System.out.println() or joined with a String using +.
class Student {
int rollNumber;
String name;
Student(int rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
@Override
public String toString() {
return "Student{rollNumber=" + rollNumber + ", name=" + name + "}";
}
}
class Main {
public static void main(String[] args) {
Student student = new Student(101, "Aman");
System.out.println(student);
System.out.println("Topper: " + student);
}
}Output:
Student{rollNumber=101, name=Aman}
Topper: Student{rollNumber=101, name=Aman}We never called toString() ourselves; Java did it for us in both lines. Remember the rules of overriding from the Method Overriding chapter: the method must be public (because it is public in Object), must return String, and should be marked with @Override so the compiler can catch spelling mistakes like tostring().
You have actually been using overridden toString() methods already. When you print a StringBuilder and see its text instead of something like StringBuilder@1b6d3586, that is StringBuilder's own toString() at work. Later, when you print an ArrayList and see [10, 20, 30], that will be ArrayList's toString().
== vs equals()
Before overriding equals(), let's be clear about the difference, which you first saw with Strings:
==compares references: are these two variables pointing to the same object in memory?equals()is meant to compare contents: do these two objects represent the same thing?
s1 ──► [ 101, "Aman" ]
s2 ──► [ 101, "Aman" ] two different objects with the same data
s1 == s2 → false (different objects)
s1.equals(s2) → we want true (same data)String already overrides equals() to compare characters, which is why "abc".equals("abc") works. For our own classes, we have to decide what "equal" means and write it ourselves.
Overriding equals() and hashCode()
Here is the standard way to write equals(). We will also override hashCode(); we will see why in a moment.
import java.util.Objects;
class Student {
int rollNumber;
String name;
Student(int rollNumber, String name) {
this.rollNumber = rollNumber;
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true; // same object
}
if (obj == null || getClass() != obj.getClass()) {
return false; // null or a different class
}
Student other = (Student) obj; // safe to cast now
return rollNumber == other.rollNumber
&& Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(rollNumber, name);
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student(101, "Aman");
Student s2 = new Student(101, "Aman");
Student s3 = new Student(102, "Priya");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(null));
System.out.println(s1.hashCode() == s2.hashCode());
}
}Output:
false
true
false
false
trueLet's walk through equals() step by step:
this == obj: if it is the very same object, it is obviously equal.obj == null || getClass() != obj.getClass(): an object is never equal tonull, or to an object of a different class.(Student) obj: the parameter type isObject, so we cast it toStudentto read its fields. The previous check guarantees this cast is safe.Finally, we compare the fields that define equality.
Objects.equals(a, b)(fromjava.util.Objects) compares two values safely even if one of them isnull.
Objects.hash(...) builds a hash code from the same fields we used in equals().
The equals() and hashCode() Contract
A hash code is an int that acts like a quick "summary" of an object. Collections such as HashSet and HashMap, which you will learn soon, use the hash code to decide where to store an object and then use equals() to confirm a match. For them to work, Java requires this rule:
If two objects are equal according to equals(), they must return the same hashCode().
The reverse is not required: two different objects are allowed to have the same hash code (this is called a collision), it just makes hash-based collections a little slower.
That is why you should always override hashCode() whenever you override equals(), and use the same fields in both. If you only override equals(), two "equal" students would usually get different default hash codes, and a HashSet would happily store both as if they were different.
A correct equals() must also follow a few common-sense rules:
Reflexive:
x.equals(x)istrue.Symmetric: if
x.equals(y)istrue, theny.equals(x)istrue.Transitive: if
x.equals(y)andy.equals(z), thenx.equals(z).Consistent: calling it again gives the same answer, as long as the objects haven't changed.
x.equals(null)is alwaysfalse.
The template shown above follows all of these rules.
A Common Mistake: Overloading Instead of Overriding
A very common bug is writing equals(Student other) instead of equals(Object obj):
class Student {
int rollNumber;
Student(int rollNumber) {
this.rollNumber = rollNumber;
}
// WRONG: this overloads equals, it does not override it
public boolean equals(Student other) {
return rollNumber == other.rollNumber;
}
}
class Main {
public static void main(String[] args) {
Student s1 = new Student(101);
Student s2 = new Student(101);
Object o2 = s2;
System.out.println(s1.equals(s2)); // calls equals(Student)
System.out.println(s1.equals(o2)); // calls Object's equals(Object)
}
}Output:
true
falseBecause the parameter type is different, this is a brand-new overloaded method, not an override. When the argument's type is Object, Java picks the original equals(Object) inherited from Object, which only checks ==. Collections always call equals(Object), so they would never use your method.
If you had added @Override above equals(Student other), the compiler would have reported an error immediately. This is the best reason to always use @Override.
getClass()
getClass() returns the actual class of an object at runtime, even when the variable's type is a parent class. This connects nicely with what we learned in the Polymorphism chapter:
class Animal {
}
class Dog extends Animal {
}
class Main {
public static void main(String[] args) {
Animal animal = new Dog();
System.out.println(animal.getClass().getSimpleName());
System.out.println(animal.getClass() == Dog.class);
System.out.println(animal.getClass() == Animal.class);
System.out.println(animal instanceof Animal);
}
}Output:
Dog
true
false
trueThe variable type is Animal, but the object is really a Dog, and getClass() reports that. Dog.class is a way to refer to the Dog class itself.
Compare this with the instanceof operator, which checks whether an object is a certain type, including parent types. A Dog is an instance of Animal, but its class is exactly Dog. That is why our equals() uses getClass(): a Student should only be equal to another Student, not to some subclass object.
A Complete Example
Let's write a Product class where two products are considered the same if they have the same product code:
import java.util.Objects;
class Product {
private final String code;
private final String name;
private final double price;
Product(String code, String name, double price) {
this.code = code;
this.name = name;
this.price = price;
}
@Override
public String toString() {
return name + " (" + code + ") - Rs. " + price;
}
// Two products are equal if they have the same code
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Product other = (Product) obj;
return Objects.equals(code, other.code);
}
// Uses the same field as equals()
@Override
public int hashCode() {
return Objects.hash(code);
}
}
class Main {
public static void main(String[] args) {
Product p1 = new Product("P100", "Keyboard", 799.0);
Product p2 = new Product("P100", "Keyboard", 799.0);
Product p3 = new Product("P200", "Mouse", 349.0);
System.out.println(p1);
System.out.println(p3);
System.out.println("p1 == p2 : " + (p1 == p2));
System.out.println("p1.equals(p2) : " + p1.equals(p2));
System.out.println("p1.equals(p3) : " + p1.equals(p3));
System.out.println("Same hashCode : " + (p1.hashCode() == p2.hashCode()));
System.out.println("Class name : " + p1.getClass().getSimpleName());
}
}Output:
Keyboard (P100) - Rs. 799.0
Mouse (P200) - Rs. 349.0
p1 == p2 : false
p1.equals(p2) : true
p1.equals(p3) : false
Same hashCode : true
Class name : ProductNotice that equals() and hashCode() both use only code. They must always agree on which fields matter.
Common Mistakes
Overriding equals() but not hashCode(). The object will misbehave in
HashSetandHashMap.Writing equals(Student) instead of equals(Object). That is overloading, not overriding. Use
@Overrideto catch it.Using == to compare objects' contents.
==checks whether two references point to the same object; useequals()for contents.Making toString() non-public. An overriding method cannot reduce visibility, so
String toString()withoutpublicwill not compile.Using fields that keep changing in hashCode(). If a field used in
hashCode()changes while the object is inside aHashSet, the set may no longer find it. Prefer fields that don't change, such as IDs (often madefinal).
Interview Tips
What is the parent of every class?
java.lang.Object.What does the default toString() return? The class name,
@, and the hash code in hexadecimal, for exampleStudent@5acf9800.Difference between == and equals()?
==compares references;equals()compares contents, if the class overrides it. The defaultequals()inObjectis the same as==.Why override hashCode() with equals()? Equal objects must have equal hash codes, otherwise hash-based collections break.
Can two unequal objects have the same hash code? Yes. That is a collision, and it is allowed.
The Main Idea
Every Java class inherits from Object, so every object has toString(), equals(), hashCode(), and getClass(). The default versions work on object identity, which is rarely what we want for our own data classes.
Override toString() for readable output, and override equals() and hashCode() together, using the same fields, whenever two different objects can represent the same thing.