gpt4 book ai didi

java - 为什么选角在这里没有像我预期的那样工作?

转载 作者:行者123 更新时间:2023-12-01 10:58:45 25 4
gpt4 key购买 nike

这是我的示例代码:

public class Bar extends Foo {
}

@SuppressWarnings("unchecked")
public class Foo {

public static void main(String[] args) {
Foo foo = new Bar();
Class<Foo> x = (Class<Foo>) foo.getClass();
System.out.println(x);
}
}

嗯,我希望这个程序输出为:Foo.class,因为我正在转换为Class,但是我在输出中看到:

class Bar

为什么?

如果我从代码中删除类型转换部分,程序甚至无法编译:

java: incompatible types
required: java.lang.Class<Foo>
found: java.lang.Class<capture#1 of ? extends Foo>

为什么编译器强制我强制转换?

最佳答案

Why?

因为对象的类是Bar ,不是Foo (您使用 new Bar() 创建了该对象),并且您已明确询问该对象它是什么类。你有一个Foo 引用对象,但这不会改变对象的实际内容。

If I remove the casting part from the code, program will not even compile:

这与 Foo 无关/Bar事物。您已给出x特定类型 ( Class<Foo> ),但 Object#getClass 输入 Class<?> .

<小时/>

来自您的评论:

Yes well, I asked the object itself, but then I cased it to a Class<Foo> and stored the data in 'x'. This is confusing me..

转换对对象根本没有影响,转换纯粹是为了更改对象的引用类型。它是同一个对象,未更改,您所做的只是更改对其引用的类型。这可能会改变您有权访问对象的哪些方面,并且如果您尝试转换为对象不属于的内容,则可能(当然)会失败。

关于java - 为什么选角在这里没有像我预期的那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33462695/

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