Java Reference
In-Depth Information
Using Overloaded Java Methods
Java resolves the method call for an overloaded method at compile time. That is, the Java
compiler determines the signature of the method that will be called when the code is
run. Consider the code for a PrintTest class shown in Listing 6-1. You may get a different
output in the second line.
Listing 6-1. Using Overloaded Methods in Java
// PrintTest.java
package com.jdojo.script;
public class PrintTest {
public void print(String str) {
System.out.println("print(String): " + str);
}
public void print(Object obj) {
System.out.println("print(Object): " + obj);
}
public void print(Double num) {
System.out.println("print(Double): " + num);
}
public static void main(String[] args) {
PrintTest pt = new PrintTest();
Object[] list = new Object[]{"Hello", new Object(), 10.5};
for(Object arg : list) {
pt.print(arg);
}
}
}
print(Object): Hello
print(Object): java.lang.Object@affc70
print(Object): 10.5
When the PrintTest class is run, all three calls to the print() method call the same
version, print(Object) of the PrintTest class. When the code is compiled, the Java
compiler sees the call pt.print(arg) as a call to the print() method with an Object
type argument (which is the type of arg ) and therefore binds this call to
print(Object) method.
 
Search WWH ::




Custom Search