• 请不要在回答技术问题时复制粘贴 AI 生成的内容
a1310747
V2EX  ›  程序员

问下这段代码最后会输出什么,为什么..

  •  
  •   a1310747 · Mar 4, 2017 · 3859 views
    This topic created in 3547 days ago, the information mentioned may be changed or developed.
    public class Test {
    public void test(Object o) {
    System.out.println("Object");
    }
    public void test(String s) {
    System.out.println("String");
    }
    public static void main(String[] args) {
    Test that = new Test();
    that.test(null);
    }
    }
    15 replies  •  2017-03-04 13:44:30 +08:00
    littleshy
    littleshy
    Mar 4, 2017
    1
    string 吧,不同类型以具体的为准。
    ml3661190
    ml3661190
    Mar 4, 2017
    2
    输出 String 具体为什么我也不清楚,坐等大神解答
    Kylinsun
    Kylinsun
    Mar 4, 2017 via Android
    3
    你传的是什么类型调用的就是什么样的方法。
    chnyang
    chnyang
    Mar 4, 2017
    4
    输出的不应该是 String 么 ..
    System.out.println("String");
    ml3661190
    ml3661190
    Mar 4, 2017
    5
    不同类型以具体的为准。理解这句话应该就没问题了,我刚刚测试了一下

    当传入的参数,未能有具体类型重载方法时,选择入参的的超类,也就是 Object 入参的方法

    当有 Object , String , boolean 三个重载的方法时,传入 null 值,编译器则会报出一个 ambiguous 的编译异常

    因为 String 跟 boolean 的方法都属于具体的类型,编译器无法判断选择那一个

    大概就是这么个意思吧
    chnyang
    chnyang
    Mar 4, 2017
    6
    @ml3661190 我是菜鸟..不知道这是不是坑,但是 test 方法唯一的一行代码只是输出一个固定的字符串而已.. 求轻喷
    yidinghe
    yidinghe
    PRO
    Mar 4, 2017 via Android
    7
    编译失败。
    chnyang
    chnyang
    Mar 4, 2017
    8
    @ml3661190 然后发现两个 test 方法....我错了
    a1310747
    a1310747
    OP
    Mar 4, 2017
    9
    @ml3661190 当有 Object , String , boolean 三个重载的方法时,传入 null 值,并不会报错 依然还是输出 String
    Cloudee
    Cloudee
    Mar 4, 2017 via iPhone
    10
    compile error
    feiyuanqiu
    feiyuanqiu
    Mar 4, 2017
    11
    jls8 §15.12.2
    ---------------
    There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is the one used at run time to perform the method dispatch.

    https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.12.2
    depress
    depress
    Mar 4, 2017
    12
    方法重载优先选子类
    ovear
    ovear
    Mar 4, 2017
    13
    优先匹配子类呀。。
    feeeeeef
    feeeeeef
    Mar 4, 2017
    14
    编译不通过
    ml3661190
    ml3661190
    Mar 4, 2017
    15
    @a1310747 这...不知道如何截图,但是我的机器上 Eclipse 确实会报错

    具体信息如下

    The method test(Object) is ambiguous for the type Test
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1469 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 16:46 · PVG 00:46 · LAX 08:46 · JFK 11:46
    ♥ Do have faith in what you're doing.