This chapter reviews method parameters and local variables, as well as method overloading and method signature.
Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters. When a method is called, the corresponding method is invoked by matching the arguments in the call to the parameter lists of the methods. The name together with the number and types of a method's parameter list is called the signature of a method. The return type itself is not part of the signature of a method.
8. Assigning to a Parameter
Answer:
Outside — so it can be called by other methods.
Assigning to a Parameter
class CheckingAccount { . . . . private int balance; public void processCheck( int amount ) { int charge; if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; // change the local copy of the value in "amount" amount = 0 ; } } public class CheckingTester { public static void main ( String[] args ) { CheckingAccount act; int check = 5000; act = new CheckingAccount( "123-345-99", "Wanda Fish", 100000 ); System.out.println( "check:" + check ); // prints "5000" // call processCheck with a copy of the value 5000 act.processCheck( check ); System.out.println( "check:" + check ); // prints "5000" --- "check" was not changed } } |
A parameter is a "one-way message" that the caller uses to send values to a method.
Within the body of a method, a parameter is used just like any variable. It can be used in arithmetic expressions, in assignment statements, and so on.
However, changes made to the parameter do not have any effect outside the method body. A parameter is a local copy of whatever value the caller passed into the method. Any changes made to it affect only this local copy.
The formal parameter amount
is the name used for the value 5000 that processCheck()
has been sent. That method changes the value held in amount
, but this has no effect on any other variable.
When the method returns to its caller, the value in the parameter amount
and the value in the local variable charge
are forgotten.
Question 8:
Say that main()
called the method with an integer literal:
act.processCheck( 7000 ); // call processCheck with the value 7000
Is this OK?