Java Instanceof 方法混乱
Java Instanceof method Confusion
假设我们有如下定义。
interface Vessel{}
interface Toy{}
class Boat implements Vessel{}
class Speedboat extends Boat implements Toy{}
主要有这些:
Boat b = new Speedboat();
和 (b instanceof Toy)
的计算结果为 true
?为什么?我的理解是b
的引用类型是Boat
,但是Boat
和Toy
没有关系所以应该是false
但是答案是true
.
根据http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
所以它检查对象的类型而不是对象的引用类型。
Boat
和Toy
没有任何关系,你是对的
但是 您在这里处理的不是 Boat
,而是存储在 Boat
变量中的实际 SpeedBoat
。 SpeedBoat
是 Toy
.
的一个实例
存储 new Speedboat()
的类型无关紧要,因为 Java 在运行时检查 实际的 对象是否是 其他的实例。
这样你就可以写类似
public boolean callSpeedBoatMethodIfPossible(Boat b) {
if (b instanceof SpeedBoat) {
((SpeedBoat)b).driveVerySpeedy();
}
}
b
的编译类型是 Boat
。但是它的 run-time 类型是 Speedboat
.
What is the difference between a compile time type vs run time type for any object in Java?
假设我们有如下定义。
interface Vessel{}
interface Toy{}
class Boat implements Vessel{}
class Speedboat extends Boat implements Toy{}
主要有这些:
Boat b = new Speedboat();
和 (b instanceof Toy)
的计算结果为 true
?为什么?我的理解是b
的引用类型是Boat
,但是Boat
和Toy
没有关系所以应该是false
但是答案是true
.
根据http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
所以它检查对象的类型而不是对象的引用类型。
Boat
和Toy
没有任何关系,你是对的
但是 您在这里处理的不是 Boat
,而是存储在 Boat
变量中的实际 SpeedBoat
。 SpeedBoat
是 Toy
.
存储 new Speedboat()
的类型无关紧要,因为 Java 在运行时检查 实际的 对象是否是 其他的实例。
这样你就可以写类似
public boolean callSpeedBoatMethodIfPossible(Boat b) {
if (b instanceof SpeedBoat) {
((SpeedBoat)b).driveVerySpeedy();
}
}
b
的编译类型是 Boat
。但是它的 run-time 类型是 Speedboat
.
What is the difference between a compile time type vs run time type for any object in Java?