java float与long,Java重载-long和float

I was trying to understand java overloading rules. Everything seems fine except following,

public static void main(String[] args) {

long aLong = 123L;

foo(aLong);

}

private static void foo(double aDouble) {

System.out.println("Foo aDouble");

}

private static void foo(Long aWrapperLong) {

System.out.println("Foo Wrapper Long");

}

private static void foo(int anInt) {

System.out.println("Foo Int");

}

private static void foo(float aFloat) {

System.out.println("Foo Float");

}

Why does the call resolve to foo(float aFloat). I understand the following from JLS,

This step uses the name of the method and the types of the argument

expressions to locate methods that are both accessible and applicable

There may be more than one such method, in which case the most

specific one is chosen.

I have intentionally used Wrapper Long here and not primitive long. Primitive long being 64 bit in size does not end up in foo(double aDouble) but 32 bit float foo(float aFloat).

解决方案

This is because of the 'most-specific' rule in JLS #15, which in turn refers to JLS #4.10, which in turn refers to #4.10.1, which states:

The following rules define the direct supertype relation among the primitive types:

double >1 float

float >1 long

long >1 int

int >1 char

int >1 short

short >1 byte

where "S >1 T" means "T is a direct subtype of S", as per JLS #4.10 immediately above this section.

So in this case, in the absence of a direct match on long, and before looking at auto-boxing, the compiler chooses the nearest available supertype, which is float, by the rules above.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值