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.
5. Scope of a Formal Parameter
Answer:
No. The formal parameter amount
can only be used by the processDeposit
method. It cannot be used by any other method.
Scope of a Formal Parameter
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 } // modified toString() method public String toString() { System.out.println( balance + "\t" + amount ); // outside of the scope of amount } } |
The scope of a formal parameter is the section of source code that can see the parameter. The scope of a formal parameter is the body of its method. For example, the scope of amount
is the body of its method.
The toString()
method cannot see amount
because it is outside the scope of amount
. The compiler will not compile this modified program.
Question 5:
Can the toString()
method see the object's instance variables, such as balance
?