如何缩小Java中方法调用的工作? [英] How does narrowing work in method invocation in Java?

查看:152
本文介绍了如何缩小Java中方法调用的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现编译时错误?
2在编译时是常量,因此应该允许缩小,因为2在字节范围内。

Why this is giving the compile time error? 2 is constant at compile time, therefore narrowing should be allowed here since 2 is in range of byte.

public class Test {


 public static void main(String[] args) {

    ForTest test=new ForTest();
    test.sum(1, 2); //compile time error here

}

}
class ForTest
{

public int sum(int a,byte b)
{
    System.out.println("method byte");
    return a+b;
}
}

错误是:
方法总和ForTest类型中的(int,byte)不适用于arguements(int,int)。

The error is: The method sum(int,byte) in the type ForTest is not applicable for the arguements (int,int).

编辑:我认为答案就在于: http://docs.oracle.com/javase/specs/ jls / se7 / html / jls-5.html#jls-5.3 但我没有得到它:(

I think the answer lies here: http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.3 but I am not getting it :(

推荐答案

您必须区分赋值转换方法调用转换

缩小原始转换

首先,看看JLS§5.1.3


22原始类型的特定转换称为缩小基元转换


  • [...]

  • [...]

int到byte,简短,或者char

int to byte, short, or char

[...]

请注意,这只能解释机制,但不能解释允许或不允许此类转换的地方。

Note, that this only explains the mechanism but not the places where such conversions are allowed or not.

作业转换

接下来,查看JLS§5.2


[...]

[...]

此外,如果表达式是byte,short,char或int类型的常量表达式(第15.28节):

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:


  • 如果变量的类型是byte,short或char,则可以使用缩小的原语转换,并且常量表达式的值可以在变量的类型中表示。

[...]

这清楚描述在赋值 byte b = 2 中从类型 int 到类型的缩小转换允许使用

This clearly describes that in the assignment byte b = 2 the narrowing conversion from type int to type byte is allowed.

方法调用转换

但是,阅读JLS§5.3时你不会读到有关缩小转换的任何内容。所以编译器正在做正确的工作。

However, when reading JLS §5.3 you will not read anything about a narrowing conversion. So the compiler is doing a correct job.

这篇关于如何缩小Java中方法调用的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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