Overloading Method Selection: Real vs. Declared Parameter Types
In Java programming, overloaded methods provide the flexibility to define multiple methods with the same name but different parameter lists. When a method is invoked, the compiler determines the appropriate method to call based on the argument list provided.
However, in certain scenarios, you may wonder if method selection considers the actual (runtime) type of the parameter instead of the declared type. Consider the following code:
interface Callee { void foo(Object o); void foo(String s); void foo(Integer i); } class CalleeImpl implements Callee { @Override public void foo(Object o) { System.out.println("foo(Object o)"); } @Override public void foo(String s) { System.out.println("foo(\"" + s + "\")"); } @Override public void foo(Integer i) { System.out.println("foo(" + i + ")"); } } public class Main { public static void main(String[] args) { Callee callee = new CalleeImpl(); Object i = new Integer(12); Object s = "foobar"; Object o = new Object(); callee.foo(i); callee.foo(s); callee.foo(o); } }
Unexpectedly, this code prints "foo(Object o)" for all three calls. Contrary to intuition, the method selection does not take into account the actual parameter types (Integer, String, and Object). Instead, it relies solely on the declared parameter types in the Callee interface.
This behavior stems from the Java language specification, which explicitly states:
When a method is invoked, the number of actual arguments and the compile-time types of the arguments are used, at compile time, to determine the signature of the method that will be invoked.
Therefore, it is crucial to note that in Java, dynamic method dispatch, where the actual method to be called is determined at runtime based on the object it is called on, only applies to the object itself, not to the parameter types.
The above is the detailed content of Does Java Method Overloading Consider Runtime Parameter Types or Only Compile-Time Declared Types?. For more information, please follow other related articles on the PHP Chinese website!