Java.Core.In equals(), you need to check that the argument equals(Object that) is of the same type as the object itself. What is the difference between this.getClass() == that.getClass() and that instanceof MyClass?

🚀 Difference Between this.getClass() == that.getClass() and that instanceof MyClass in equals()

When implementing equals(), checking the type of that is important to avoid class mismatches.
There are two common ways to check if an object is of the same type:

  1. this.getClass() == that.getClass()
    • Ensures strict class equality (no inheritance allowed).
  2. that instanceof MyClass
    • Allows subclass instances to be considered equal.

Both approaches have different behaviors when dealing with inheritance.


1️⃣ this.getClass() == that.getClass() → Strict Type Check

This method only allows objects of the exact same class to be equal.

  • Inheritance is NOT allowed—a subclass object is not equal to a superclass object.

Example: Using this.getClass() == that.getClass()

class Person {
    String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || this.getClass() != obj.getClass()) return false; // Strict class check
        Person person = (Person) obj;
        return name.equals(person.name);
    }
}

class Employee extends Person {
    String company;

    public Employee(String name, String company) {
        super(name);
        this.company = company;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person("Alice");
        Employee e = new Employee("Alice", "Google");

        System.out.println(p.equals(e)); // ❌ false (Different classes)
    }
}

📌 Why does equals() return false?

  • e is an Employee, and p is a Person.
  • Since e.getClass() == Employee.class and p.getClass() == Person.class, they fail the strict class check.

2️⃣ that instanceof MyClass → Allows Subclass Comparison

This method allows equality checks across inheritance.

  • A subclass can be considered equal to a superclass.
  • It is less strict than this.getClass() == that.getClass().

Example: Using that instanceof Person

class Person {
    String name;

    public Person(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Person)) return false; // Allows subclasses
        Person person = (Person) obj;
        return name.equals(person.name);
    }
}

class Employee extends Person {
    String company;

    public Employee(String name, String company) {
        super(name);
        this.company = company;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p = new Person("Alice");
        Employee e = new Employee("Alice", "Google");

        System.out.println(p.equals(e)); // ✅ true (Because Employee extends Person)
        System.out.println(e.equals(p)); // ✅ true (Even though one is Employee, one is Person)
    }
}

📌 Why does equals() return true?

  • e instanceof Person is true, so it passes the type check.
  • Since both p and e have the same name, they are considered equal.

3️⃣ Key Differences Between getClass() and instanceof

Featurethis.getClass() == that.getClass()that instanceof MyClass
Allows Subclasses?❌ No (Only exact class match)✅ Yes (Superclass and subclass can be equal)
StrictnessVery strictMore flexible
Common Use CaseWhen objects must be exactly the same typeWhen a subclass should be treated as equal
Example of equals() ResultPerson.equals(Employee) == falsePerson.equals(Employee) == true

4️⃣ When to Use Which Approach?

Use this.getClass() == that.getClass() When:

Two objects should only be equal if they are the exact same class.
✔ You want strict type safety.
✔ You are designing a class where subclass behavior should not affect equality.

Use that instanceof MyClass When:

✔ You want to allow subclass comparisons.
✔ You are following Liskov’s Substitution Principle (subclasses should behave like their parent class).
✔ You are creating a hierarchy where an equals() comparison should be valid for any subclass.


📌 Final Summary

CheckAllows Subclasses?When to Use?
this.getClass() == that.getClass()❌ NoWhen equality should be strictly between the same class
that instanceof MyClass✅ YesWhen subclasses should be considered equal to the superclass

By following these rules, your equals() method will work correctly and predictably in Java collections like HashSet and HashMap! 🚀

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.