隐式类型强制转换不适用于方法参数? [英] Implicit type cast not working for method parameters?

查看:55
本文介绍了隐式类型强制转换不适用于方法参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段:

class TypeCast{
  public static void main(String[] args){
    byte by = 4;     //compiler casts int literal to byte

    doCasting(4);    //Compilation Error: external type casting is required. WHY ?

  }

  public static void doCasting(byte by){

  }

}

我认为上面的代码片段是不言自明的.当 int 文字分配为 byte 类型时,编译器自动执行所需的强制转换.当我们调用带有int常量的 byte 参数的方法时,不会发生相同的事情.为什么?

I think above code snippet is quite self-explanatory. While int literal assignment to byte type, compiler does the required cast automatically. Same thing does not happen when we call a method taking byte parameter with int literal. Why?

推荐答案

这是分配上下文(

This is the difference between an assignment context (JLS 5.2) and an invocation context (JLS 5.3) for conversions.

分配上下文转换包括:

此外,如果该表达式是类型为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,并且常量表达式的值可表示为变量的类型,则可以使用缩窄基元转换.

在调用上下文转换中不存在 .

That isn't present in the invocation context conversions.

除了可能简化重载解析(如果您有)之外,我不清楚为什么要用这种方式设计语言.

It's not clear to me why the language was designed that way, other than to possibly simplify overload resolution - if you had:

doCasting(5);
...
doCasting(int x) {}
doCasting(byte b) {}

然后,您可以为它们中的任何一个辩称是最佳匹配".- byte 是比 int 更具体的类型,但是如果您认为文字是 int 类型,则 byte重载使得需要进行转换,而 int 重载则不需要转换.

then you could argue for either of them being the "best match" - byte is a more specific type than int, but if you think of the literal as being of type int, then the byte overload makes requires a conversion whereas the int overload doesn't.

通过使 byte 重载根本不适用,问题得以解决.

By making the byte overload simply not applicable, the question is removed.

这篇关于隐式类型强制转换不适用于方法参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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