Java Constructors, Stack, Stack Frames, Heap, Garbage Collection (GC)

When you create a new object, the constructor is called first. One of the very first things the constructor does is call super() (the object’s super-class’s constructor). Then from there, if that super-class isn’t class Object, it follows up the tree until it reached class Object. When that’s done, Object’s constructor stack frame is popped off, and it goes down to Object’s current sub-class. That constructor executes, and gets its stack frame popped off the stack, and follows down all the way down to the final, concrete, sub-class. Now we have an object that holds all of its super-classes in it, and has space for all of the instance variables those objects may contain.

You can call this(); (with arguments, too) from an overloaded constructor to another overloaded constructor that contains the “common” initialization code, which then calls super(); But the call to super(); must be the first statement in the destination constructor (this is true for both this(); and super();)

Also, super(); is implicitly declared in any constructor that doesn’t use this();, you can choose to put it in there, but it better be first. Always remember, before any code can execute within the object, the superclass must first be constructed.

This is valid:

class Dog {
public Dog(int i, String pupName) {
// Note there's no return type allowed in constructors!
this(pupName, i);
}
public Dog() {
// Different argument list (none here, actually),
// so it's ok to overload
this("Moose", 3);
}
public Dog(String pupName, int i) {
// same arguments, different order (VALID!)
}
}

Primitives and references are disposed of after the method returns. A variable that is local holds its state until the method is finished executing. It may hold its state and be “alive”, thus residing on the stack until its frame is popped, but it will be out of scope (and not accessible) until its stack frame is at the top of the stack. Then the count-down begins until its frame is popped. An instance variable is stored with its object, and is in scope, and alive for the duration of the object’s life. All objects live on the heap, even ones referred to solely by a local variable. They have the same lifespan of any other object.

Garbage Collection (GC) is neat, as soon as an object has no valid references, it becomes GC bait. Death to ye non-referenced objects.

Tags: ,

Leave a Reply