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.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS