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.

Objects Are Mutable

You can change the contents of an object by making an assignment to one of its instance variables. For example, to "move" a rectangle without changing its size, you could modify the x and y values:

    box.x = box.x + 50;
    box.y = box.y + 100;

The result is shown in the figure:

We could take this code and encapsulate it in a method, and generalize it to move the rectangle by any amount:

  public static void moveRect (Rectangle box, int dx, int dy) {
    box.x = box.x + dx;
    box.y = box.y + dy;

The variables dx and dy indicate how far to move the rectangle in each direction. Invoking this method has the effect of modifying the Rectangle that is passed as an argument.

    Rectangle box = new Rectangle (0, 0, 100, 200);
    moveRect (box, 50, 100);
    System.out.println (box);

prints java.awt.Rectangle[x=50,y=100,width=100,height=200].

Modifying objects by passing them as arguments to methods can be useful, but it can also make debugging more difficult because it is not always clear which method invocations do or do not modify their arguments. Later, I will discuss some pros and cons of this programming style.

In the meantime, we can enjoy the luxury of Java's built-in methods, which include translate, which does exactly the same thing as moveRect, although the syntax for invoking it is a little different. Instead of passing the Rectangle as an argument, we invoke translate on the Rectangle and pass only dx and dy as arguments.

    box.translate (50, 100);

The effect is exactly the same.

Last Update: 2011-01-24