#689 – References and Objects

A variable whose type is a reference type can be declared without making the variable point to an instance of that type (an object).  At this point, the value of the variable will be null.

A reference-typed variable can later be assigned to refer to an instance of the appropriate type, or it can be assigned at the point where it is declared.

            Dog myDog;
            myDog = new Dog("Kirby", 13);

            Dog yourDog = new Dog("Ruby", 2);

A reference-typed variable can be re-assigned to refer to a difference instance of the type.  (If an object is no longer referenced by any variables, it will eventually be garbage collected).

            Dog jack = new Dog("Jack", 15);
            Dog kirby = new Dog("Kirby", 13);

            Dog currentDog = jack;
            currentDog = kirby;

Notice also in this example that more than one reference-typed variable can refer to the same object.

Advertisements