Check if an object is of the same class as this?

12,596

Solution 1

Use

this.getClass() == anotherObject.getClass()

instead of instanceof. This will return true only if the two object belong to the same class (it's safe to check if class objects are equal by reference). And after that you may compare the id.

Solution 2

You should read this article for problems when implementing equals.

To make it short: use this.getClass()==other.getClass() instead of instanceof, because otherwise the equals() relationship will not be transitive (superInstance.equals(subInstance) will be true, but subInstance.equals(superInstance) will be false).

Share:
12,596
PurkkaKoodari
Author by

PurkkaKoodari

Updated on June 04, 2022

Comments

  • PurkkaKoodari
    PurkkaKoodari almost 2 years

    I have a base class for multiple data object types in Java. I want to create an equals method in the base class, that works directly when inherited.

    Equality is determined by the two objects

    1. belonging to subclasses of the base class. This is easily achievable using

      if (!(anObject instanceof BaseClass))
          return false;
      
    2. having the same ID. The ID field is defined by the base class so we can here test that.

      if (this.id != ((BaseClass) anObject).id)
          return false;
      
    3. belonging to the same class. This is where I have the problem. Two objects may be of different types (and so be in different lists), but have the same ID. I have to be able to distinguish them. How can I do this?