Stavo facendo uno di questi test Java on-line e mi è stato chiesto questa domanda:java.lang.Object o = 1; // perché viene compilato?
D: Indicate corretta assegnazione:
Long l = 1;
Double d = 1;
Integer i = 1;
String s = 1;
Object o = "1";
System.out.println(o);
o = 1;
System.out.println(o);
Si prega di provare voi stessi prima di andare oltre.
Beh vi posso dire mi sono sbagliato, ho studiato ed ho trovato:
//Long l = 1; //cannot widen and then box
Long ll = 1L;//no need to widen, just box
//Double d = 1;//cannot widen and then box
Double dd = 1d;//no need to widen, just box
Integer i = 1;//no need to widen, just box
//String s = 1;//cannot do implicit casting here
Object o = "1";//this compiles and is just plain weird
System.out.println(o);//output is 1
o = 1;//this also compiles and is also weird
System.out.println(o);//output is 1
Qualcuno può dire perché:
Object o = 1;
e Object o = "1";
compilazione e l'uscita 1 in entrambi i casi questo mi sta sconcertando
Grazie
Wow, grazie per la risposta, ma devo dirti che mi sento così stupido ora dovrei saperlo. – Ramo
@Ramo: non mettere in discussione qualcosa che non sai sarebbe stupido :-) – Grundlefleck