Skip to main content
ICT
Lesson A4 - Object Behavior
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

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.