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.
6. What Statements See
Answer:
Yes.
What Statements See
public class CheckingAccount { private String accountNumber; private String accountHolder; private int balance; . . . . public void processDeposit( int amount ) { // scope of amount starts here balance = balance + amount ; // scope of amount ends here } public void processCheck( int amount ) { // scope of amount starts here int charge; incrementUse(); if ( balance < 100000 ) charge = 15; else charge = 0; balance = balance - amount - charge ; // scope of amount ends here } } |
A method's statements can see the instance variables of their object. They cannot see the parameters and local variables of other methods. Look again at the CheckingAccount
class.
Two methods are using the same identifier, amount
, for two different formal parameters. Each method has its own formal parameter completely separate from the other method. This is OK. The scopes of the
two parameters do not overlap so the statements in one method cannot "see" the formal parameter of the other method.
For example the statement
balance = balance - amount - charge ;
from the second method can only see the formal parameter of that method. The scope of the formal parameter of the other method does not include this statement.
Of course, the formal parameters of any one parameter list must all have different names.
Question 6:
Could the two formal parameters (of the two methods) named amount
be of different
types? (For example, could one be an int
and the other a long
?)