5

オーバーロードされた関数、、compute1()を以下で使用しようとすると、コンパイルエラーが発生しますcompute2()compute5()

package com.example.test.reflect;

class JLS15Test2
{
    int compute1(Object o1, Integer i, Integer j)         { return 1; }
    int compute1(String s1, Integer i, int j)             { return 2; }

    int compute2(Object o1, Integer i, int j)             { return 3; }
    int compute2(String s1, Integer i, Integer j)         { return 4; }

    int compute3(Object o1, Integer i, int j)             { return 5; }
    int compute3(String s1, Integer i, int j)             { return 6; }

    int compute4(Object o1, Integer i, Integer j)         { return 7; }
    int compute4(String s1, Integer i, Integer j)         { return 8; }

    int compute5(Object o1, Integer i, Object j)          { return 9; }
    int compute5(String s1, Integer i, int j)             { return 10; }


    public static void main(String[] args) 
    {
        JLS15Test2 y = new JLS15Test2();

        // won't compile:
        // The method compute1(Object, Integer, Integer) is ambiguous 
        // for the type JLS15Test2
        // System.out.println(y.compute1("hi", 1, 1));

        // Neither will this (same reason)
        // System.out.println(y.compute2("hi", 1, 1));
        System.out.println(y.compute3("hi", 1, 1));
        System.out.println(y.compute4("hi", 1, 1));

        // neither will this (same reason)
        // System.out.println(y.compute5("hi", 1, 1));
    }
}

JLSセクション15.12を読んだ後、私は理解していると思います...オーバーロードされたメソッドのマッチングのフェーズ2(ボクシング/アンボクシングが許可され、varargsはありません)で、「最も具体的なメソッド」を決定するとき、JLSは(事実上)最も特定のメソッドは、正式なパラメーターが他の適用可能なメソッドのサブタイプであるメソッドであり、プリミティブとオブジェクト(egintInteger)が互いにサブタイプになることはありません。したがってInteger、はのサブタイプであり、はのサブタイプですが、とIntegerはw / r / tサブタイプの比較と互換性がないため、/ペアのどちらにも最も具体的な方法はありません。intintIntegerintcompute1()compute2()

(incompute3()と引数compute4()を持つメソッドは、String引数を持つメソッドよりも具体的であるObjectため、プログラムは6と8を出力します。)

私の推論は正しいですか?

4

2 に答える 2

0

はい、あなたの推論は正しいです。

于 2011-05-19T17:13:48.627 に答える
0

プリミティブintとボックス化された整数を受け取る別のメソッドを追加すると、どちらが適切なメソッドであるかを解決できます。

int compute6(int i) { return 11;}
int compute6(Integer i){return 12;}
...
System.out.println(y.compute6(1));

それに基づいて、それは、個別の型の関係だけでなく、異なるパラメーター間の相互作用に関係していると思います。

于 2011-05-19T17:15:00.627 に答える