Java:コンパイル時の解決と「最も具体的なメソッド」
-
15-11-2019 - |
質問
オーバーロード関数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を読んだ後、私は私が理解していると思います... "最も具体的な方法"を決定する際の一致する過負荷メソッドの順序で、JLSが言う(有効)最も具体的な方法は、正式なパラメータが他の適用可能なメソッドのサブタイプであり、プリミティブとオブジェクト(int
およびInteger
)が互いにサブタイプではありません。そのため、Integer
はInteger
のサブタイプで、int
はint
のサブタイプですが、Integer
とint
は互換性のないW / R / Tサブタイプ比較であるため、compute1()
/ compute2()
ペアのどちらも特に具体的な方法がありません。
(compute3()
およびcompute4()
では、String
引数を使用したメソッドは、Object
引数を指定した方法よりも具体的です。プログラムは6と8)を印刷します。)
私の推論は正しいですか?
解決
Yes, your reasoning is correct.
他のヒント
If you add another method that just takes a primitive int and a boxed Integer, it is able to resolve which one is the proper method to called:
int compute6(int i) { return 11;}
int compute6(Integer i){return 12;}
...
System.out.println(y.compute6(1));
Based on that, I'd imagine that it has something to do with the interaction between the different parameters, and not just the separate type relationships.