Local
VariablesTopOverloaded MethodsParameters vs. Instance Variables

Parameters vs. Instance Variables

Parameters are used to pass information from one object (or method) to another. If we look at the call of move in onMouseDrag of Drag2Shirts:

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

The parameters communicate to the move method of selectedShirt information about how far to move. The actual parameter refers to the information being sent to the object (in this case 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 move 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). Note that the scope of a formal parameter is only the method whose header it appears in.

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.


Local
VariablesTopOverloaded MethodsParameters vs. Instance Variables