All the rar files have the same 
password : http://learning4you.blogspot.com/

Monday, November 10, 2008

References to objects. in java

References to Objects

As you work with objects, one important thing going on behind the scenes is the use of references to those objects. When you assign objects to variables, or pass objects as arguments to methods, you are passing references to those objects, not the objects themselves or copies of those objects.

An example should make this clearer. Examine Listing 4.4, which shows a simple example of how references work.


Listing 4.4. A references example.
 1: import java.awt.Point;
2:
3: class ReferencesTest {
4: public static void main (String args[]) {
5: Point pt1, pt2;
6: pt1 = new Point(100, 100);
7: pt2 = pt1;
8:
9: pt1.x = 200;
10: pt1.y = 200;
11: System.out.println("Point1: " + pt1.x + ", " + pt1.y);
12: System.out.println("Point2: " + pt2.x + ", " + pt2.y);
13: }
14: }

Point1: 200, 200
Point2: 200, 200

Analysis
In the first part of this program, you declare two variables of type Point (line 5), create a new Point object to pt1 (line 6), and finally, assign the value of pt1 to pt2 (line 7).

Now, here's the challenge. After changing pt1's x and y instance variables in lines 9 and 10, what will pt2 look like?

As you can see, pt2's x and y instance variables were also changed, even though you never explicitly changed them. When you assign the value of pt1 to pt2, you actually create a reference from pt2 to the same object to which pt1 refers (see Figure 4.1). Change the object that pt2 refers to, and you also change the object that pt1 points to, because both are references to the same object.

Figure 4.1 : References to objects.

Note
If you actually do want pt1 and pt2 to point to separate objects, you should use new Point() for both lines to create separate objects.

The fact that Java uses references becomes particularly important when you pass arguments to methods. You'll learn more about this later today, but keep these references in mind.

Technical Note
There are no explicit pointers or pointer arithmetic in Java as there are in C-like languages-just references. However, with these references, and with Java arrays, you have most of the capabilities that you have with pointers without the confusion and lurking bugs that explicit pointers can create.

0 comments:

Related Posts with Thumbnails