分配问题OCJP;为什么我不能将 int 传递给 short? [英] Assignment issue OCJP; why can't I pass an int to a short?

查看:27
本文介绍了分配问题OCJP;为什么我不能将 int 传递给 short?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两段代码.一个有效,另一个无效,但两者似乎都在做相同的事情.这有效:

I have two pieces of code. One works, another doesn't, but both seem to do identical things. This works:

short s=7;

但下面的代码没有.相反,它给出了错误:

but the below code doesn't. Instead, it gives error:

不能将 int 分配给 short

can't assign int to short

我知道一个整数字面量默认是int,但是如果可以直接在上面赋值,那为什么不能在传递给方法时呢?

I know an integer number literal by default is int, but if it can be assigned directly above, then why not when passing to a method?

class Demo1{
    public static void main(String[] args){
        new Demo1().go(7);
    }
    void go(short s){System.out.println("short");}
}

推荐答案

赋值和方法重载解析的规则不同:

The rules are different for assignment and for method overload resolution :

对于分配,JLS 说:

For assignment the JLS says :

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

A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

对于重载解析,JLS 15.12.2.2. 说:

方法 m 通过子类型化适用当且仅当满足以下条件:

The method m is applicable by subtyping if and only if both of the following conditions hold:

对于 1 ≤ i ≤ n,要么:
* Ai <: Si (§4.10), 或
* Ai 可通过未经检查的转换(第 5.1.9 节)转换为某种类型的 Ci,并且 Ci <: Si.

For 1 ≤ i ≤ n, either:
* Ai <: Si (§4.10), or
* Ai is convertible to some type Ci by unchecked conversion (§5.1.9), and Ci <: Si.

这里的 Ai 是传递给方法的参数的类型(在您的情况下为 int,因为 7 是一个 int 文字).Si 是方法形式参数的类型(在您的情况下为 short).Ai <: Si 表示 Ai 是 Si 的子类型.intnot short 的子类型(反之亦然),这就是为什么编译器不接受 newDemo1().go(7);.

Here Ai is the type of the parameter passed to the method (int in your case, since 7 is an int literal). Si is the type of the method's formal parameters (short in your case). Ai <: Si means that Ai is a sub-type of Si. int is not a sub-type of short (the opposite is true), which is why the compiler doesn't accept new Demo1().go(7);.

这篇关于分配问题OCJP;为什么我不能将 int 传递给 short?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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