java的编译和连接方法_Java:编译时解析和“最具体的方法”
如果您嘗試在下面使用它們,重載函數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說(實際上)最多特定方法是其形式參數是其他適用方法的子類型的方法,而原語和對象(例如int和Integer)從不是彼此的子類型.因此Integer是Integer的子類型,int是int的子類型,但是Integer和int是不兼容的w / r / t子類型比較,因此compute1()/ compute2()對都沒有最具體的方法.
(在compute3()和compute4()中,使用String參數的方法比使用Object參數的方法更具體,因此程序打印6和8.)
我的推理是否正確?
總結
以上是生活随笔為你收集整理的java的编译和连接方法_Java:编译时解析和“最具体的方法”的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 迅雷看看播放器怎么样?
- 下一篇: java传参怎么理解_如何理解Java的