Java Object


When you create a class in Java, you create a new data type. You can use this type to declare such objects. However, receiving a class is a two-step process:


In the preceding sample programs, a line similar to the following is used to declare an object of the Rect:

Rect myrect =  new Rect();

This statement simply combines the two steps described. Each step is more clearly shown below:

Rect myrect;  // declare reference to object
myrect = new Rect();   // allocate a Rect object

The first line declares "myrect" as a reference to an object of type Rect. At this point, "myrect" does not yet refer to an actual object. The next line allocates an object and assigns a reference to it to "myrect". After the second line executes, you can use 'myrect' as if it were a Rect object. But in reality, "myrect" simply holds, in essence, the memory address of the actual Rect object.


Assigning Object Reference Variables

Object reference variables work differently than you expect when an assignment occurs.

Rect r1 = new Rect();
Rect r2 = r1;

You might think that r2 is begin assigned a reference to a copy of the object referred to by r1. That is, you might think that r1 and r2 refer to separate and distinct objects. However, this would be wrong. Instead, after this fragment executes, r1 and r2 will both refer to the same object. This assignment of r1 to r2 did not allocate any memory or copy any part of the original object. It simply makes r2 refer to the same object as does r1. This, any changes made to the object through r2 will affect the object to which r1 is referring since they are the same object.

Assigning object reference variables

Although r1 and r2 both refer to the same object, they are not linked in any other way. For example, a subsequent assignment to r1 will simply unhook r1 from the original object without affecting the object or affecting r2.

Rect r1 = new Rect();
Rect r2 = r1;
//...
r1 = null;

Here, r1 has been set to null, but r2 still points to the original object.