Course contentsShow
← Java
Lesson 572 of 2,87013. The Object Class and Common MethodsFree lesson

Using getClass for Type Comparison

Understand how to compare object types at runtime using getClass() and the difference from instanceof.

Using getClass for Type Comparison

You'll learn how to use getClass() to check exact type matches at runtime and understand why it differs from instanceof.

The Core Idea

When you call getClass() on an object, you get a Class object representing its exact runtime type. You can compare these Class objects using == to determine if two objects are exactly the same type—not just compatible types like instanceof checks.

Think of it like checking someone's passport versus checking if they're allowed in a country. instanceof asks "can this object act as this type?" (citizenship or visa). getClass() asks "is this object's birth certificate exactly this nationality?"—no substitutes accepted.

Type Comparison with getClass()

String text = "Hello";
Object obj = "World";

// Using getClass() for exact type comparison
if (text.getClass() == String.class) {
    System.out.println("text is exactly a String"); // ✓ Prints
}

if (obj.getClass() == String.class) {
    System.out.println("obj is exactly a String"); // ✓ Prints (runtime type is String)
}

if (obj.getClass() == Object.class) {
    System.out.println("Never prints"); // ✗ Runtime type is String, not Object
}

getClass() vs instanceof

class Animal {}
class Dog extends Animal {}

Dog myDog = new Dog();

// instanceof: checks "is-a" relationship (includes subclasses)
System.out.println(myDog instanceof Animal);  // true (Dog IS-A Animal)

// getClass(): checks exact type only
System.out.println(myDog.getClass() == Animal.class);  // false (Dog ≠ Animal)
System.out.println(myDog.getClass() == Dog.class);     // true (exact match)

Use instanceof when polymorphism matters. Use getClass() when you need to enforce exact type matching (common in certain equals() implementations to prevent subtle inheritance bugs).

Key Takeaway: getClass() compares exact runtime types using ==, rejecting subclasses, while instanceof accepts any compatible type in the inheritance hierarchy.