devxlogo

Which Class is Returned by getClass()?

Which Class is Returned by getClass()?

When a class is instantiated, the subsequent object is actually an instance of the most derived class in the class hierarchy. A point of confusion for some programmers is that if the inheritance hierarchy is several levels deep, which class actually gets instantiated and which method actually gets invoked (in the case of overridden methods)? Consider these definitions for classes Base and Derived. The class Derived extends Base.

 1.   public class Base {2.   }3.   public class Derived extends Base {4.   }5. 6.    // Test the getClass() method for the above classes.7.    Base base = new Base();8.    Base derived = new Derived();9. 10. System.out.println("Class for base object  = " + 11.                    base.getClass().toString());12. System.out.println("Class for derived object = " +                  13.                    derived.getClass().toString());

On Line 7, a new class of type Base is instantiated. On Line 8, another class of type Base is instantiated. However, note that the actual instantiation (done by the new operator) creates a class of type Derived, which is implicitly cast to its superclass Base. On Lines 10-13, the runtime classes of the two object references (base and derived are printed out). The output will be:

 Class for base object = BaseClass for derived object = Derived

Even though the object referenced by base is of type Base, the runtime class is Derived. The type of the class that is actually instantiated is the one referenced by the new operator.

See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist