290 Methods Chapter 6 Called square with int (Fedora web server)
290 Methods Chapter 6 Called square with int argument: 7 Called square with double argument: 7.5 Fig. 6.16Using overloaded methods (part 2 of 2). Fig. 6.16 Overloaded methods are distinguished by their signature a combination of the method s name and its parameter types. If the Java compiler looked only at method names during compilation, the code in Fig. 6.16 would be ambiguous the compiler would not know how to distinguish between the two square methods. Logically, the compiler uses longer mangled or decorated names that include the original method name, the types of each parameter and the exact order of the parameters to determine if the methods in a class are unique in that class. For example, in Fig. 6.16, 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 squaremethod that specifies a doubleparameter. If a method foo s definition begins as void foo( int a, float b ) then the compiler might use the logical name foo of int and float. If the parameters are specified as void foo( float a, int b ) then the compiler might use the logical name foo of float and int. Note that the order of the parameters is important to the compiler. The preceding two foo methods are considered to be distinct by the compiler. The logical names of methods used by the compiler did not mention the return types of the methods, because methods cannot be distinguished by return type. The program in Fig. 6.17 illustrates the compiler errors generated when two methods have the same signature and different return types. Overloaded methods can have different return types, but must have different parameter lists. Also, overloaded methods need not have the same number of parameters. Common Programming Error 6.17 Creating overloaded methods with identical parameter lists and different return types is a syntax error. 1 // Fig. 6.17: MethodOverload.java 2 // Overloaded methods with identical signatures and 3 // different return types. 4 5 // Java extension packages 6 import javax.swing.JApplet; 7 Fig. 6.17Compiler error messages generated from overloaded methods with Fig. 6.17 identical parameter lists and different return types (part 1 of 2). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01