[英]Incompatible operand types
I have created a class and its child. 我创建了一个类及其子级。 Now, I need to check if the child is the instance of parent but I get Incompatible operand types. 现在,我需要检查子代是否是父代的实例,但是得到不兼容的操作数类型。
class Vehicle {
}
class Car extends Vehicle {
}
public class Test {
public static void main(String[] args) {
Vehicle v = new Vehicle();
Car c = new Car();
if (c instanceof v) {
}
}
}
The instanceof
keyword needs to be used as instanceof
关键字需要用作
ReferenceTypeExpression instanceof ReferenceType
You are using it as 您正在使用它作为
ReferenceTypeExpression instanceof ReferenceTypeExpression
You should instead have 你应该有
if (c instanceof Vehicle) {
The above explains the correct use of the instanceof
operator, but take note of JB Nizet's comment . 上面说明了instanceof
运算符的正确用法,但请注意JB Nizet的comment 。
Use isAssignableFrom()
method in Class
class. 在Class
类中使用isAssignableFrom()
方法。
if (c.getClass().isAssignableFrom(v.getClass())) {
...
}
instanceof需要将参考变量a与类b进行比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.