java.lang.Object o = 1; //为什么要编译?

Ram*_*amo 5 java autoboxing

我正在做这些在线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);
Run Code Online (Sandbox Code Playgroud)

请在继续之前自己尝试一下.

好吧,我可以告诉你我弄错了,我调查了一下,发现:

//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
Run Code Online (Sandbox Code Playgroud)

有人能说出原因:

Object o = 1;Object o = "1";

在这两种情况下编译输出1,这让我感到困惑.

非常感谢

Ale*_*x B 9

"1"是String类的实例,String是Java中Object类的子类(与任何其他类一样).1被装入一个Integer,它也是从Object派生的.