This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Java in General and the fly likes Can superclass object find the subclass type that is the true type of instance? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "Can superclass object find the subclass type that is the true type of instance?" Watch "Can superclass object find the subclass type that is the true type of instance?" New topic
Author

Can superclass object find the subclass type that is the true type of instance?

Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Let's say I have a class B that extends A with the constructor:

Is there a way to have something like the following in A?

where it would print "B" since that is the actual class, not A.
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1007
    
    3
Try this:



Class B isn't public because I didn't bother to put it in a separate file. If you do, then it should be.

Ryan
Robert Paris
Ranch Hand

Joined: Jul 28, 2002
Posts: 585
Thanks, now I'm guessing that this only works on an instance level, correct?

So if I have a static section in class A, then when class B is loaded, it would NOT also invoke the static section in A, right?

Geoffrey Falk
Ranch Hand

Joined: Aug 17, 2001
Posts: 171
    
    1
When B is loaded, its superclass A is loaded first. So yes, the static section is invoked.


Sun Certified Programmer for the Java 2 Platform
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Well, it's usually only necessary to load a class once in a given JVM. So it's possible that executing code will refer to class A, causeing it to be loaded, and then later on the code refers to B, causing it to be loaded. Since A was already loaded (by itself), it will not be reloaded just before B is loaded. So: you can guarantee that a static initializer in A will run sometime before a static initializer in B - but it's hard to say exactly when. (Unless you follow exactly what code is getting executed.) And when A is loaded the first time, you have no real way of knowing if it's getting loaded just because B is getting loaded, or for some other reason. So there's not really an equivalent of getClass() that you can use to figure out what's going on.
[ May 10, 2005: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
 
GeeCON Prague 2014
 
subject: Can superclass object find the subclass type that is the true type of instance?