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.
10. Can't use the Same Name in the Same Scope
Answer:
No — the scope starts where the variable was declared and continues to the end of its block.
Sometimes a local variable is declared in the middle of a block, close to the
statement which first uses it.
Often, local variables are declared at the beginning of a block so that their scope is the
entire block. But this is not a requirement of syntax.
Can't use the Same Name in the Same Scope
class CheckingAccount { . . . . private int balance; public void processCheck( int amount ) { int amount; incrementUse(); if ( balance < 100000 ) amount = 15; // which amount ??? else amount = 0; // which amount ??? balance = balance - amount ; // which amount ??? } } |
Don't use the same identifier twice in the same scope. The example shows this mistake.
The scope of the formal parameter amount
overlaps the scope of the local variable (also named amount
), so this is a mistake. (In terms of "one-way glass", both identifiers are inside the box.)
This is a different situation than a previous example where two methods used the same name for their formal parameters. In that situation the scopes did not overlap and there was no confusion. (In terms of "one-way glass", each identifier was inside its own box.)
Question 10:
Can the same identifier be used as a name for a local variable in two different methods?