Is the name
of a method inside or outside
the glass box?
Outside — so it can be "seen" and used by other methods.
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. For example:
class CheckingAccount { . . . . private int balance; 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 ; } } class CheckingTester { CheckingAccount act; public static void main ( String[] args ) { int check = 5000; act = new CheckingAccount( "123-345-99", "Wanda Fish", 100000 ); // prints "5000" System.out.println( "check:" + check ); // call processCheck with a copy of the value 5000 act.processCheck( check ); // prints "5000" --- "check" was not changed System.out.println( "check:" + check ); } }
The formal parameter amount
is
the name used by processCheck()
for the value 5000
that it has been given by the caller.
The method can change the value held in amount
,
but this has no effect on the caller's variables.
Say that main()
called the method with an integer literal:
act.processCheck( 7000 ); // call processCheck with the value 7000
Is this OK? What would be the effect of this statement in the method:
amount = 0 ; // change the local copy in "amount"