Parameters, Local Variables, and Overloading
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
?