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.
16. Method Overloading
Answer:
mystA sum: 15 mystB sum: 20
The instance variable in mystB
did not change.
The trick: the parameter sum
of the second method shadowed the instance varaible.
Method Overloading
Overloading is when two or more methods of a class have the same name but have different parameter lists. When a method is called, the correct method is picked by matching the actual parameters in the call to the formal parameter lists of the methods.
Review: another use of the term "overloading" is when an operator calls for different operations depending on its operands. For example +
can mean integer addition, floating point addition, or string concatenation depending on its
operands.
Say that two processDeposit()
methods were needed:
- One for ordinary deposits, for which there is no service charge.
- One for other deposits, for which there is a service charge.
public class CheckingAccount { . . . . private int balance; . . . . public void processDeposit( int amount ) { balance = balance + amount ; } public void processDeposit( int amount, int serviceCharge ) { balance = balance + amount - serviceCharge; } } |
The above code implements these requirements. Here is an examplemain()
method that uses both methods:
class CheckingAccountTester { public static void main( String[] args ) { CheckingAccount bobsAccount = new CheckingAccount( "999", "Bob", 100 ); bobsAccount.processDeposit( 200 ); // statement A bobsAccount.processDeposit( 200, 25 ); // statement B } } |
Question 16:
Examine main()
.
Which method, processDeposit(int)
or processDeposit(int, int)
does each statement call?
- statement A calls
- statement B calls