gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:11 26 4
gpt4 key购买 nike

我正在做这些在线 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,这让我很困惑。

非常感谢

最佳答案

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

关于java.lang.Object o = 1;//为什么编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2346624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com