Java: risoluzione del tempo di compilazione e "metodo più specifico"
-
15-11-2019 - |
Domanda
Le funzioni sovraccariche compute1()
, compute2()
e compute5()
Cause Errori di compilazione Se si tenta di usarli di seguito:
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));
}
}
.
Dopo aver letto la sezione JLS 15.12, penso di capire ... in fase 2 (boxe / unboxing consentito, senza varg) di metodi di abbinamento sovraccarico, quando si determinano il "metodo più specifico", il JLS dice (in effetti) Che il metodo più specifico è quello i cui parametri formali sono i sottotipi di altri metodi applicabili, i primitivi e gli oggetti (ad es. int
e Integer
) non sono mai sottotipi dell'altro. Quindi Integer
è un sottotipo di Integer
, e int
è un sottotipo di int
, ma Integer
e int
sono incompatibili con componenti di sottotipo di sottotipo con r / t, quindi nessuna delle coppie compute1()
/ compute2()
ha un metodo più specifico.
(considerando che in compute3()
e compute4()
il metodo con l'argomento String
è più specifico del metodo con l'argomento Object
, quindi il programma stampa 6 e 8.)
Il mio ragionamento è corretto?
Soluzione
Yes, your reasoning is correct.
Altri suggerimenti
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.