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.
18. Return Type is Not Part of the Signature
Answer:
No.
The names of the formal parameters are not part of the signature, nor is the return type. The signatures of the two methods are:
chargePenalty( int )
chargePenalty( int )
Both methods have the same signature.
Return Type is Not Part of the Signature
It might seem strange that the return type is not part of the signature. But a potentially confusing situation is avoided by keeping the return type out of the signature. Say that there were two methods that differ only in their return type:
float chargePenalty( int amount ) { ... } int chargePenalty( int penalty ) { ... }
and that main used one of the methods:
class CheckingAccountTester
{
public static void main( String[] args )
{
CheckingAccount bobsAccount = new CheckingAccount( "999", "Bob", 100 );
double result = bobsAccount.chargePenalty( 60 )
;
}
}
Which method should be called?
Either method matches the statement, since both have and int
parameter and both return a type that can be converted to double
. (Both int
and float
can be converted
to double
.)
To avoid confusion in situations like this, the return type is not counted as part of the signature.
Question 18:
Say that a class has these two methods:
public void changeInterestRate( double newRate ) { ... }
public void changeInterestRate( int newRate ) { ... }
Do these methods have unique signatures?