The instanceof approach works well, but it returns true for parent classes too, which might not always be desirable.
If you only want to check for the exact class (without considering inheritance), use getClass() instead:
if (obj.getClass() == B.class) {
System.out.println("Exact type is B");
} else if (obj.getClass() == C.class) {
System.out.println("Exact type is C");
}
Differences from instanceof:
-
getClass() only matches the exact class (not subclasses).
-
Safer when you don’t want superclass matches.
-
Doesn’t work well for polymorphic checks.