4

私は2つのコードを持っています。1つは機能し、もう1つは機能しませんが、どちらも同じことをしているようです。これは機能します:

short s=7;

しかし、以下のコードはそうではありません。代わりに、エラーが発生します。

int を short に代入できません

デフォルトで整数リテラルint

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

5 に答える 5

0

割り当てでは、コンパイラがどの引数にキャストするかは明らかです。

short s=7; //here is no doubt that it must be cast to short

おそらく仮想である可能性があるメソッド呼び出しでは、決定できません。

go(7); //here it could be anything

コンパイラは、型に互換性のある署名を見つけようとします。

void go(Integer i); // via auto boxing
void go(Number i); // autoboxing and supertype

キャストを試行しません。つまり、以下は機能しません。

void go(short s); // short is neither a super type nor a subtype of int
void go(byte b); // byte is neither a super type nor a subtype of int

私はむしろgo(new Integer(7))呼び出すことを期待していませんvoid go(Short s)。それは、型の階層関係にないすべての型で同じです。

于 2015-03-15T11:40:06.120 に答える