Wednesday, May 10, 2006

References

Pointers in Java are called references. I guess pointers are called references because you can't do any arithmetic pointer operations on them (reference needed).

Before creating objects from the class, you will need a reference that can point to where the object is stored in memory. A reference is a kind of variable that stores addresses to memory locations.

A reference is necessary when you want to handle an object. If you want to access the object you need a reference. Also, an object that is not pointed to, may get destroyed anytime by the garbage collector, because it assumes that the program no longer need to access the object.

Concept: An object no longer pointed to, is a dead object.

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        Dog dog;
    }
}

The statement Dog dog; creates a new reference. The name of the reference is dog, and the reference may point to objects of type Dog. The reference does not yet point to anything, because it contains no value.