You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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), 10 is an int literal.
  • For non-private methods, the compiler would first check if it can use autoboxing to turn the int into an Integer to match the foo(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.
  • int can be widened directly to float—this is a valid, allowed primitive conversion in Java. Since there's no foo(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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:46:22