这里发生了什么? java分配问题OCJP [英] What is happening here ? java assignment issue OCJP

查看:130
本文介绍了这里发生了什么? java分配问题OCJP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两段代码,一段是有效的,另一段没有,但两者似乎做同样的事情

Two pieces of code, one works, another doesn't, but both seem to do identical things

这是有效的

short s=7;

但这不是。这给出了错误,无法将int赋值为short。默认情况下
i knw整数是否为 int 但是如果它可以直接在上面分配,那么为什么不在传递给方法时呢?

but this doesn't . this gives error , can't assign int to short. i knw a integer number literal by default is int but if it can be assigned directly above , then why not when passing to 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 :

For赋值JLS说:

For assignment the JLS says :


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

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<: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 literal)。 Si 是方法的形式参数的类型(在您的情况下)。 Ai< ;: Si 表示Ai是Si的子类型。 int short 的子类型(相反的情况属实),这就是为什么编译器不接受 new Demo1()。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);.

这篇关于这里发生了什么? java分配问题OCJP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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