Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1064
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 171
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When B is loaded, its superclass A is loaded first. So yes, the static section is invoked.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic