我正在做这些在线 Java 测试之一,我被问到这个问题:
问:指出正确的分配:
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);
在您继续之前,请自己尝试一下。
好吧,我可以告诉你我弄错了,我调查了一下,发现:
//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
有人能说出原因吗:
Object o = 1;
和Object o = "1";
在这两种情况下编译并输出 1,这让我很困惑。
非常感谢