Overloaded method selection based on the parameter's real type

后端 未结 7 1381
悲哀的现实
悲哀的现实 2020-11-22 01:39

I\'m experimenting with this code:

interface Callee {
    public void foo(Object o);
    public void foo(String s);
    public void foo(Integer i);
}

class          


        
7条回答
  •  悲哀的现实
    2020-11-22 02:30

    Java looks at the reference type when trying to determine which method to call. If you want to force your code you choose the 'right' method, you can declare your fields as instances of the specific type:

    Integeri = new Integer(12);
    String s = "foobar";
    Object o = new Object();
    

    You could also cast your params as the type of the param:

    callee.foo(i);
    callee.foo((String)s);
    callee.foo(((Integer)o);
    

提交回复
热议问题