Home >Java >javaTutorial >How Does Java's Static Typing Affect Overloaded Method Invocation Based on Parameter Type?
Overloaded Method Invocation Based on Parameter Type
In Java, polymorphic methods, known as overloaded methods, allow the definition of multiple methods with the same name but distinct parameter types. Method selection, the process of determining which overloaded method to invoke, is based on the static type of the declared parameters, not their actual type.
Consider the following code:
interface Callee { void foo(Object o); void foo(String s); void foo(Integer i); } class CalleeImpl implements Callee { // Method implementations omitted for brevity } 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);
This code prints "foo(Object o)" three times, despite the actual types of the parameters being Integer, String, and Object, respectively. This is because Java uses static typing, meaning that the type of a variable is determined at compile time and remains constant throughout the program's execution.
To overcome this limitation and invoke methods based on the actual parameter type, one can consider using reflection or generics. However, it's important to note that such techniques introduce additional complexity and may not always be the most appropriate solution.
The above is the detailed content of How Does Java's Static Typing Affect Overloaded Method Invocation Based on Parameter Type?. For more information, please follow other related articles on the PHP Chinese website!