p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   Java Basics (http://p2p.wrox.com/forumdisplay.php?f=199)
-   -   static field with class instance (http://p2p.wrox.com/showthread.php?t=44576)

prakash.suthar June 28th, 2006 03:06 AM

static field with class instance
 
Static variable is class variable and all the instance (object) of class share the single copy of static. It is none of use to call the static variable with class instance (object), though we can call.
I just wanted to know that how this functionality is achieved.
1.When class is loaded in memory, class variable i.e. static variable is created and when the instance (object) of that class is created, reference of that static variable is passed to the class instance (object)…
OR
2.At runtime, when static variable is used, compiler check that instance of which class invoke the static variable, and after identification compiler use the static variable from class memory…
So, what happens actually, either of two above or something else is happened when we call like “obj.staticfield”?

bhavesh bhanushali July 1st, 2006 06:22 PM

I guess the second option would be more efficinet , since it would be easy for the compiler to check wheter the class to which the object belongs to , has a "static" feild or method and if so then those can be directly called by the reference object .


panacea July 3rd, 2006 01:41 AM

The implementation is actually a mix between your two approaches. The compiler compiles references to static variables and methods into special bytecodes that specifically denote that the reference or call is static. Then when the JVM executes the bytecodes, it knows to look up the static variables or methods in the class definition, rather than in an object instantiation.

More detail can be found here: http://mrl.nyu.edu/~meyer/jvmref/ref--19.html (Definition of the bytecode for retrieving a static class member.)

After reading up on this subject, I'm still confused how different classloaders fit into the situation. Does a class loaded by two different classloaders have two instances of static member variables? How does the getstatic bytecode know which classloaders to use -- does it always use the system classloader? If anyone else has information on this, I'd love to hear it.

Jon Emerson
http://www.jonemerson.net/


All times are GMT -4. The time now is 05:34 AM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.