Java方法重载行为异常:调用foo(10)为何输出float而非Integer?
Why does
foo(10) call the float overload instead of Integer? Let's start by looking at your code first:
public class Clazz { private static String foo(Integer value) { return "Integer"; } private static String foo(float value) { return "float"; } public static void main(String[] args) { System.out.println(foo(10)); System.out.println(foo(10f)); } }
You expected the output to be Integer float, but got float float instead—here's why that happens:
The key issue boils down to how Java resolves overloaded private methods and the priority of type conversions:
- When you call
foo(10),10is anintliteral. - For non-private methods, the compiler would first check if it can use autoboxing to turn the
intinto anIntegerto match thefoo(Integer)overload. But for private methods, the compiler skips considering autoboxing/unboxing entirely during overload resolution. It only looks for valid primitive type widening conversions. intcan be widened directly tofloat—this is a valid, allowed primitive conversion in Java. Since there's nofoo(int)overload to match exactly, the compiler picks the next best option:foo(float).
To put it simply: Private methods use static binding at compile time, and the overload resolution logic for them doesn't include autoboxing. So your int literal gets widened to float instead of being boxed to Integer.
内容的提问来源于stack exchange,提问作者Álvaro Nieto
相关产品推荐
相关产品推荐

