Search code examples
javainheritancepolymorphism

How to find out that instance is from Class c and not subclass?


instanceof shows if an instance is from class C or a subclass of C.

Is there a way to make sure that an instance is not a subclass?


Solution

  • In that case use getClass() and compare it with the desired class:

    boolean sameClass = someObject.getClass() == YourTargetClass.class;