java main参数null,带有null参数的Java方法调度

Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?

Object testVal = null;

test.foo(testVal); // dispatched to foo(Object)

// test.foo(null); // compilation problem -> "The method foo(String) is ambiguous"

public void foo(String arg) { // More-specific

System.out.println("foo(String)");

}

public void foo(Object arg) { // Generic

System.out.println("foo(Object)");

}

In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?

Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?

Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.

解决方案

Which version of Java are you using? With 1.6.0_11 the code (pasted below) compiles and runs.

I am sure its obvious why foo(testVal) goes to foo(Object).

The reason why foo(null) goes to foo(String) is a little complex. The constant null is of type nulltype, which is a subtype of all types. So, this nulltype extends String, which extends Object.

When you call foo(null) compiler looks for the overloaded method with most specific type. Since String is more specific then Object that is the method that gets called.

If you had another overload that was as specific as String, say foo(Integer) then you would get a ambiguous overload error.

class NullType {

public static final void main(final String[] args) {

foo();

}

static void foo()

{

Object testVal = null;

foo(testVal); // dispatched to foo(Object)

foo(null); // compilation problem -> "The method foo(String) is ambiguous"

}

public static void foo(String arg) { // More-specific

System.out.println("foo(String)");

}

public static void foo(Object arg) { // Generic

System.out.println("foo(Object)");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值