Java重载-long和float [英] Java overloading - long and float

查看:158
本文介绍了Java重载-long和float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解Java重载规则.一切都很好,除了关注

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");
}

为什么呼叫会解析为foo(float aFloat).我从JLS了解以下内容,

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.

我在这里故意使用了包装长包装,而不是原始包装.长为64位的原始长号不会以foo(double aDouble)结尾,而是以32位浮点foo(float aFloat)结尾.

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).

问题为什么Java隐式地(不强制转换)将"long"转换为"float"?进一步阐明了该问题的答案.

The question Why does Java implicitly (without cast) convert a `long` to a `float`? further clarifies the answer to this question.

推荐答案

这是因为

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 浮动

浮动> 1

long> 1 int

long >1 int

int> 1 字符

int> 1

short> 1 字节

根据本节正上方的JLS#4.10,"S> 1 T"表示"T是S的直接子类型".

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

因此,在这种情况下,在long上没有直接匹配的情况下,并且在查看自动装箱之前,编译器会根据上述规则选择最近的可用超类型,即float.

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.

这篇关于Java重载-long和float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆