class Animal{
String name;
Animal(String name){
this.name=name;
}
}
class Cat extends Animal{
String color;
Cat(String name,String color){
super(name);
this.color=color;
}
}public class test {
public static void main(String args[]){
Cat a = new Cat("catName","blank");
Dog b = new Dog("dogName","yellow");
Animal c = new Animal("name");
System.out.println(a instanceof Cat);
System.out.println(a instanceof Animal);
System.out.println(b instanceof Dog);
System.out.println(b instanceof Animal);
System.out.println(c instanceof Animal);
System.out.println(c instanceof Dog);
System.out.println(a instanceof Dog);
System.out.println(b instanceof Cat);
}
} 注释掉后三行,运行的结果全是true,问题就在后三行中。倒数第三行没有错误,但是后两行都报错,没办法编译运行。报错说的是Incompatible conditional operand types Dog and Cat(不相容的条件操作数类型猫狗),instanceof明明是一个返回boolean类型的运算符,判断是false的时候返回不就行了。错在哪里了?
String name;
Animal(String name){
this.name=name;
}
}
class Cat extends Animal{
String color;
Cat(String name,String color){
super(name);
this.color=color;
}
}public class test {
public static void main(String args[]){
Cat a = new Cat("catName","blank");
Dog b = new Dog("dogName","yellow");
Animal c = new Animal("name");
System.out.println(a instanceof Cat);
System.out.println(a instanceof Animal);
System.out.println(b instanceof Dog);
System.out.println(b instanceof Animal);
System.out.println(c instanceof Animal);
System.out.println(c instanceof Dog);
System.out.println(a instanceof Dog);
System.out.println(b instanceof Cat);
}
} 注释掉后三行,运行的结果全是true,问题就在后三行中。倒数第三行没有错误,但是后两行都报错,没办法编译运行。报错说的是Incompatible conditional operand types Dog and Cat(不相容的条件操作数类型猫狗),instanceof明明是一个返回boolean类型的运算符,判断是false的时候返回不就行了。错在哪里了?
忘了把Dog类写上去了,现在加上。
class Dog extends Animal{
String color;
Dog(String name,String color){
super(name);
this.color=color;
}
}
class test {
public static void main(String args[]){
Cat a = new Cat("catName","blank");
Dog b = new Dog("dogName","yellow");
Animal c = new Animal("name");
System.out.println(a instanceof Cat);
System.out.println(a instanceof Animal);
System.out.println(b instanceof Dog);
System.out.println(b instanceof Animal);
System.out.println(c instanceof Animal);
System.out.println(c instanceof Dog);
//System.out.println(a instanceof Dog);
instanceofTest(a); //测试结果:false;赞同[1楼的结论:只有相关的类型(有继承、实现关系)的才能instanceof]
//System.out.println(b instanceof Cat);
}
public static void instanceofTest(Animal a)
{
System.out.println(a instanceof Dog);
}
}
instanceof左边的操作数的编译类型必须是后面的类的父类(继承或实现都可以)或者跟它一样才能用instanceof
a 的编译类型是Cat
b 的编译类型是Dog
Cat(Dog)不是Dog(Cat)的父类,也不同于Dog类,所以倒数第二(一)条错误
意思是说,instanceof只能判定一个类是不是另一个类的子类? 是子类了就返回true,前面是父类的话就报false,如果不是父子类关系的话就无法编译了。是这个意思吗? 加上三楼我补充的代码,视频上讲的是:instanceof可以判定“猫是不是动物”,“狗是不是动物”,“猫是不是狗”和“狗是不是猫”,返回结国分别是true,true,false,false,并没有说编译错误的事。 我是在视频上听课抄下来的例子,视频应该用的是jdk1.5吧,难道是改变规则了?
a和b,即猫和狗的实体,而猫和狗都是继承与Animal,不可以比较吗?
谢谢您帮助我找错误。
我是看的视频教程上面讲的,他讲的时候用的是jdk1.4还是1.5,是现在改了吗?
谢谢你。
我还不怎么会看API,我没有在API中找到这个关键字的说明。在哪个包里你知道吗?