Skip to main content
ICT
Lesson A4 - Object Behavior
 
Main   Previous Next
 

B. Parameters and Arguments page 4 of 11

  1. Parameters and arguments are used to pass information to a method. Parameters are used when defining a method, and arguments are used when calling the method.

  1. In Code Sample 4-1, we use the DrawingTool’s forward method to move the myPencil object. However, we must tell the forward method how far to move, or it would not be a very useful method. We do this by passing an argument to it. In our example, we sent it the int value 100. The turnLeft method will default to 90 degrees if we don’t pass it a value. If we want it to turn a different amount, we can send how far left we want it to turn in degrees.

    myPencil.turnLeft(60);

  2. When a method is called with an argument, the parameter receives the value of the argument. If the data type is primitive, we can change the value of the parameter within the method as much as we want and not change the value of the argument passed in the method call. Object variables, however, are references to the object’s physical location. When we pass an object’s variable name, we get a copy of that reference. Therefore, when we use the passed in reference to access this object within the method, we are in fact working with the same data of the object that was passed as an argument and have the ability to directly change the data inside the object. This can get very messy if the programmer doesn’t realize what is going on.

  1. When defining a method, the list of parameters can contain multiple parameters. For example:

    When this method is called, the arguments fed to the doMath method must be the correct type and must be in the same order. The first argument must be an int. The second argument can be a double or an int (since an int will automatically be converted by Java).

  2. Arguments can be either literal values (2, 3.5) or variables (a, x).

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.