Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 12, 1999

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 = Base
Class 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.
Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date