gpt4 book ai didi

java - 多态性和混淆实例

转载 作者:行者123 更新时间:2023-11-29 10:13:59 25 4
gpt4 key购买 nike

我很困惑一个对象如何成为两个不同类的instanceof。例如:

EnglishTest x = new EnglishQuiz();
if (x instanceof EnglishTest){
System.out.print("P");
}
if (x instanceof EnglishQuiz){
System.out.print("P");
}

在这两种情况下,我都会打印出“P”。我的问题是为什么?

我知道 xEnglishTest 类型,但是因为我正在做 new EnglishQuiz 不应该意味着我正在创建一个实例EnglishQuiz 而不是 EnglishTest?这里发生了什么?

最佳答案

如果此行编译:

EnglishTest x = new EnglishQuiz();

那么一定有一个is-a EnglishTest之间的关系和 EnglishQuiz ;具体来说,一个 EnglishQuiz必须是 EnglishTest 的子类型,很像 IntegerNumber .

因此,x instanceof EnglishTest是真的,同理Integer instanceof Number是真的。一个EnglishQuiz是一个 EnglishTest ,毕竟。

查看 Java 语言规范 Section 15.20.2 :

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

因为 EnglishQuiz总是可以转换为 EnglishTest (这样的转换称为向上转换并且总是被允许的,因为对象总是可以归类为其父类(super class)型),instanceof运算符(operator)返回 true .

另一种可视化方式可能是这样的:

          Object
|
Number
/ \
Integer Float
/ \
Pos. Neg.
/ \ / \
1 2 -4 -5

x instanceof y如果 y 将返回真与 x 的类型相同或者如果你能联系到 yx 上升.

关于java - 多态性和混淆实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23451825/

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