Overloading del costruttore – REVIEWED -
Eh sì, devo proprio dirlo. Ho sbagliato !!! Non che non mi capiti mai, ma questa volta l’ho anche scritto sul mio blog, quindi DEVO riparare e salvare quello che ancora rimane della mia reputazione. L’errore è stato nel post in cui si parlava dell’overloading del costruttore, rimetto di seguito il giochino che avevo pubblicato:
1 2 3 4 5 6 7 8 | public class OverloadResolver { public OverloadResolver(Object param) { System.out.println("Construttore con parametro Object"); } public OverloadResolver(Object[] param) { System.out.println("Costruttore con parametro Object[]"); } } |
La domanda era: "Qualcuno sa cosa succede se faccio questa chiamata:"
1 2 3 4 5 | ...... public static void main(String[] args) { OverloadResolver or = new OverloadResolver(null); } ...... |
Ingenuamente mi son fidato. Nel senso che ho considerato buona la risposta che ho trovato nell’articolo che ho letto in internet, (in realtà volevo anche rispondere ora che so la risposta corretta, ma non riesco più a trovarlo, poi vi dico se lo trovo) e quindi non mi sono posto il problema di testarlo. Quando ieri, un caro vecchio amico, mi ha fatto gentilmente notare, e per gentilmente intendo a modo suo, che la risposta da me data non era quella giusta, in quanto diffidando dalla risposta ha testato l’esempio, e il risultato non era quello che avevo dato. Quindi, eseguendo l’esempio, il risultato è che viene richiamata la funzione:
1 2 3 | public OverloadResolver(Object[] param) { System.out.println("Costruttore con parametro Object[]"); } |
Perchè ? Il motivo lo incollo, così come l’ho trovato in internet, ovviamente sul sito della sun:
So the third rule is to choose the most "specific" method. The rule is: if any method still under consideration has parameter types that are assignable to another method that’s also still in play, then the other method is removed from consideration. This process is repeated until no other method can be eliminated. If the result is a single "most specific" method, then that method is called. If there’s more than one method left, the call is ambiguous. Suppose that you have the methods: f(float) f(double) In this case, the parameter types for the first method are assignable to the parameter types of the second method, that is, it’s legal to say: double = float through a widening primitive conversion. By contrast, saying: float = double is not valid without a cast. Based on this third rule, f(double) is removed from the set of possible methods to call, and therefore f(float) is called.
Morale della favola? La prossima volta non fidatevi degli articoli trovati in rete senza prima averli provato. Ciauu
Nessun commento
Non c’è ancora nessun commento.
RSS feed dei commenti a questo articolo.
