Methods of the same name can be declared in the same class, as long as they have different sets of parameters (determined by the number, types and order of the parameters)this is called method overloading. When an overloaded method is called, the Java compiler selects the appropriate method by examining the number, types and order of the arguments in the call. Method overloading is commonly used to create several methods with the same name that perform the same or similar tasks, but on different types or different numbers of arguments. For example, Math methods abs, min and max (summarized in Section 6.3) are overloaded with four versions each:
Our next example demonstrates declaring and invoking overloaded methods. You will see examples of overloaded constructors in Chapter 8.
Declaring Overloaded Methods
In our class MethodOverload (Fig. 6.13), we include two overloaded versions of a method called squareone that calculates the square of an int (and returns an int) and one that calculates the square of a double (and returns a double). Although these methods have the same name and similar parameter lists and bodies, you can think of them simply as different methods. It may help to think of the method names as "square of int" and "square of double," respectively. When the application begins execution, class MethodOverloadTest's main method (Fig. 6.14, lines 610) creates an object of class MethodOverload (line 8) and calls the object's method testOverloadedMethods (line 9) to produce the program's output (Fig. 6.14).
Figure 6.13. Overloaded method declarations.
(This item is displayed on pages 258 - 259 in the print version)
1 // Fig. 6.13: MethodOverload.java 2 // Overloaded method declarations. 3 4 public class MethodOverload 5 { 6 // test overloaded square methods 7 public void testOverloadedMethods() 8 { 9 System.out.printf( "Square of integer 7 is %d ", square( 7 ) ); 10 System.out.printf( "Square of double 7.5 is %f ", square( 7.5 ) ); 11 } // end method testOverloadedMethods 12 13 // square method with int argument 14 public int square( int intValue ) 15 { 16 System.out.printf( " Called square with int argument: %d ", 17 intValue ); 18 return intValue * intValue; 19 } // end method square with int argument 20 21 // square method with double argument 22 public double square( double doubleValue ) 23 { 24 System.out.printf( " Called square with double argument: %f ", 25 doubleValue ); 26 return doubleValue * doubleValue; 27 } // end method square with double argument 28 } // end class MethodOverload |
Figure 6.14. Overloaded method declarations.
(This item is displayed on page 259 in the print version)
1 // Fig. 6.14: MethodOverloadTest.java 2 // Application to test class MethodOverload. 3 4 public class MethodOverloadTest 5 { 6 public static void main( String args[] ) 7 { 8 MethodOverload methodOverload = new MethodOverload(); 9 methodOverload.testOverloadedMethods(); 10 } // end main 11 } // end class MethodOverloadTest
|
In Fig. 6.13, line 9 invokes method square with the argument 7. Literal integer values are treated as type int, so the method call on line 9 invokes the version of square at lines 1419 that specifies an int parameter. Similarly, line 10 invokes method square with the argument 7.5. Literal floating-point values are treated as type double, so the method call on line 10 invokes the version of square at lines 2227 that specifies a double parameter. Each method first outputs a line of text to prove that the proper method was called in each case. In line 10, note that the argument value and return value are displayed with the format specifier %f and that we did not specify a precision in either case. By default, floating-point values are displayed with six digits of precision if the precision is not specified in the format specifier.
Distinguishing Between Overloaded Methods
The compiler distinguishes overloaded methods by their signaturea combination of the method's name and the number, types and order of its parameters. If the compiler looked only at method names during compilation, the code in Fig. 6.13 would be ambiguousthe compiler would not know how to distinguish between the two square methods (lines 1419 and 2227). Internally, the compiler uses longer method names that include the original method name, the types of each parameter and the exact order of the parameters to determine whether the methods in a class are unique in that class.
For example, in Fig. 6.13, the compiler might use the logical name "square of int" for the square method that specifies an int parameter and "square of double" for the square method that specifies a double parameter (the actual names the compiler uses are messier). If method1's declaration begins as
void method1( int a, float b )
then the compiler might use the logical name "method1 of int and float." If the parameters are specified as
void method1( float a, int b )
then the compiler might use the logical name "method1 of float and int." Note that the order of the parameter types is importantthe compiler considers the preceding two method1 headers to be distinct.
Return Types of Overloaded Methods
In discussing the logical names of methods used by the compiler, we did not mention the return types of the methods. This is because method calls cannot be distinguished by return type. The program in Fig. 6.15 illustrates the compiler errors generated when two methods have the same signature and different return types. Overloaded methods can have different return types if the methods have different parameter lists. Also, overloaded methods need not have the same number of parameters.
Figure 6.15. Overloaded method declarations with identical signatures cause compilation errors, even if the return types are different.
1 // Fig. 6.15: MethodOverloadError.java 2 // Overloaded methods with identical signatures 3 // cause compilation errors, even if return types are different. 4 5 public class MethodOverloadError 6 { 7 // declaration of method square with int argument 8 public int square( int x ) 9 { 10 return x * x; 11 } 12 13 // second declaration of method square with int argument 14 // causes compilation error even though return types are different 15 public double square( int y ) 16 { 17 return y * y; 18 } 19 } // end class MethodOverloadError
|
Common Programming Error 6.11
Declaring overloaded methods with identical parameter lists is a compilation error regardless of whether the return types are different. |
Introduction to Computers, the Internet and the World Wide Web
Introduction to Java Applications
Introduction to Classes and Objects
Control Statements: Part I
Control Statements: Part 2
Methods: A Deeper Look
Arrays
Classes and Objects: A Deeper Look
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
GUI Components: Part 1
Graphics and Java 2D™
Exception Handling
Files and Streams
Recursion
Searching and Sorting
Data Structures
Generics
Collections
Introduction to Java Applets
Multimedia: Applets and Applications
GUI Components: Part 2
Multithreading
Networking
Accessing Databases with JDBC
Servlets
JavaServer Pages (JSP)
Formatted Output
Strings, Characters and Regular Expressions
Appendix A. Operator Precedence Chart
Appendix B. ASCII Character Set
Appendix C. Keywords and Reserved Words
Appendix D. Primitive Types
Appendix E. (On CD) Number Systems
Appendix F. (On CD) Unicode®
Appendix G. Using the Java API Documentation
Appendix H. (On CD) Creating Documentation with javadoc
Appendix I. (On CD) Bit Manipulation
Appendix J. (On CD) ATM Case Study Code
Appendix K. (On CD) Labeled break and continue Statements
Appendix L. (On CD) UML 2: Additional Diagram Types
Appendix M. (On CD) Design Patterns
Appendix N. Using the Debugger
Inside Back Cover