tags:

views:

834

answers:

2
  1. When an object is instantiated in Java, what is really going into memory?
  2. Are copies of parent constructors included?
  3. Why do hidden data members behave differently than overridden methods when casting?

I understand the abstract explanations that are typically given to get you use this stuff correctly, but how does the JVM really do it.

+2  A: 

I think you'll find this to be a comprehensive example:

http://www.onjava.com/pub/a/onjava/2005/01/26/classloading.html

Deano
+11  A: 

When an object is instantiated, only the non-static data is actually "Created", along with a reference to the type of object that created it.

None of the methods are ever copied.

The "Reference" to the class that created it is actually a pointer dispatch table. One pointer exists for each method that is available to the class. The pointers always point to the "correct" (usually the lowest/most specific in the object tree) implementation of the method.

That way if you have a top-level call to another method, but the other method has been overridden, the overridden method will be called because that's where the pointer in the table points. Because of this mechanism, it shouldn't take more time to call an overridden method than a top-level one.

The pointer table + member variables are the "Instance" of a class.

The variable issue has to do with a completely different mechanism, "Name spaces". Variables aren't "Subclassed" at all (They don't go into the dispatch table), but public or protected variables can be hidden by local variables. This is all done by the compiler at compile time and has nothing to do with your runtime object instances. The compiler determines which object you really want and stuffs a reference to that into your code.

The scoping rules are generally to favor the "Nearest" variable. Anything further away with the same name will just be ignored (shadowed) in favor of the nearer definition.

To get a little more specific about memory allocation if you are interested: all "OBJECTS" are allocated on the "Heap" (Actually something amazingly more efficient and beautiful than a true heap, but same concept.) Variables are always pointers--Java will never copy an object, you always copy a pointer to that object. Variable pointer allocations for method parameters and local variables are done on the stack, but even though the variable (pointer) is created on the stack, the objects they point to are still never allocated on the stack.

I'm tempted to write an example, but this is already too long. If you want me to type out a couple classes with an extends relationship and how their methods and data effect the code generated I can... just ask.

Bill K