How do I check an object's type in Java when it extends a common superclass?

The simplest and most common way to check an object’s type in Java is using the instanceof operator. It allows you to determine whether an object is an instance of a specific class or its subclass.

Example Usage:

if (obj instanceof B) {
    System.out.println("Object is an instance of B");
} else if (obj instanceof C) {
    System.out.println("Object is an instance of C");
} else {
    System.out.println("Object is not an instance of B or C");
}

Why use instanceof?

  • It works at runtime and correctly identifies subclasses.
  • It prevents ClassCastException, unlike direct casting.
  • It is straightforward and widely used.