Using getClass() on Object Instances
You'll learn how to retrieve an object's actual runtime class using the getClass() method, which is essential for understanding polymorphic behavior.
The Core Idea
Every object in Java inherits the getClass() method from the Object class. When you call getClass() on any object instance, you get back a Class object that represents the actual runtime type of that object—not the declared reference type. This is crucial when working with polymorphism, where a variable's declared type might be a superclass or interface, but the actual object could be any subclass.
Think of getClass() as asking an object, "What are you really?" rather than "What does your name tag say?" The reference variable is just a label, but getClass() reveals the true identity.
When This Matters
Object obj = "Hello"; // declared as Object, but actually a String
Class<?> cls = obj.getClass();
System.out.println(cls.getName()); // prints: java.lang.String
List<String> list = new ArrayList<>();
Class<?> listClass = list.getClass();
System.out.println(listClass.getName()); // prints: java.util.ArrayList
In the first example, even though obj is declared as Object, getClass() correctly identifies it as a String. In the second, the List reference points to an ArrayList, and getClass() reveals that concrete implementation.
Practical Use
Use getClass() when you need to inspect what type of object you're actually dealing with at runtime—perfect for debugging, logging, or making type-aware decisions in generic code.
Key Takeaway: getClass() returns the runtime Class object of any instance, revealing its true type regardless of how the reference variable was declared—essential for understanding polymorphic references.