The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Aliasing

Remember that when you make an assignment to an object variable, you are assigning a reference to an object. It is possible to have multiple variables that refer to the same object. For example, this code:

    Rectangle box1 = new Rectangle (0, 0, 100, 200);
    Rectangle box2 = box1;

generates a state diagram that looks like this:

Both box1 and box2 refer or "point" to the same object. In other words, this object has two names, box1 and box2. When a person uses two names, it's called aliasing. Same thing with objects.

When two variables are aliased, any changes that affect one variable also affect the other. For example:

    System.out.println (box2.width);
    box1.grow (50, 50);
    System.out.println (box2.width);

The first line prints 100, which is the width of the Rectangle referred to by box2. The second line invokes the grow method on box1, which expands the Rectangle by 50 pixels in every direction (see the documentation for more details). The effect is shown in the figure:

As should be clear from this figure, whatever changes are made to box1 also apply to box2. Thus, the value printed by the third line is 200, the width of the expanded rectangle. (As an aside, it is perfectly legal for the coordinates of a Rectangle to be negative.)

As you can tell even from this simple example, code that involves aliasing can get confusing fast, and it can be very difficult to debug. In general, aliasing should be avoided or used with care.



Last Update: 2011-01-24