Local VariablesTopDragging TshirtsParameters vs. Instance Variables

Parameters vs. Instance Variables

Parameters are used to pass information from one object (or method) to another. Call of move in onMouseDrag of Drag2Shirts:

    selectedShirt.move( point.getX() - lastPoint.getX(), 
                                         point.getY() - lastPoint.getY());

communicates to the move method of selectedShirt the information about how far to move. The actual parameter refers to the information being sent to the object. In this example there are two actual parameters: point.getX() - lastPoint.getX() and point.getY() - lastPoint.getY(). These are associated with the formal parameters, xOffset and yOffset of the method:

    public void move(double xOffset, double yOffset) { ... }

When you send a message to an object, it is as though we execute an assignment statement associating the formal parameters with the value of the actual parameters. In the above example, it is as though we executed:

    xOffset = point.getX() - lastPoint.getX();
    yOffset = point.getY() - lastPoint.getY();

Thus the formal parameters refer to the same values as the actual parameters (whether the actual parameters are themselves variables or complicated expressions, as in the above case).

The matching up of actual and formal parameters is determined solely by the order in which the parameters are written, not by names. Also, the type of an actual parameter must always match the type declared for the formal parameter. However, as usual we may use an integer for an actual parameter where a double is expected.

The key differences between parameters and instance variables is that parameters are used to transmit information to a method that it needs. The information comes from whatever object is sending the message. Instance variables, on the other hand, save information inside an object so that it is available again when it is needed. Look back at each of the example methods we wrote and determine why the parameters were needed.


Local VariablesTopDragging TshirtsParameters vs. Instance Variables