这段程序有什么错误?不是很长。

来源:百度知道 编辑:UC知道 时间:2024/06/20 14:43:09
public class Cla1 {
static int c=-8;
public static void main(String args[]) {
Cla1 cl = new Cla1();
Thread th=new Thread();
boolean bl=cl instanceof Cla1;
boolean b2=th instanceof Cla1; //为什么这里显示“条件操作数类型 Thread 和 Cla1 不兼容”
System.out.println(bl);
System.out.println(b2);
}
}
那我用别的对象,它显示错误,用别的数据类型,显示不匹配,那这个运算符号有什么用?
难道就这个运算符的结果只能是true?
能举一个结果为flase的例子吗?

th instanceof Cla1

因为 th 和 Cal1的类型非常明确,你的 th 根本不是 Thread

所以无须判断。编译器都能看出来他不是这个类型的

只有有继承关系的两个类之间才能使用instanceof关键字 如果是毫不相关的两个类用instanceof是错误的 编译都会通不过

如果就想比较 可以将th强转成Object然后再instanceof

答案补充:false的例子见下面 c1 instanceof Child2
public class test {
public static void main(String[] args) {
Parent p = new Parent();
Parent c1 = new Child1();
Parent c2 = new Child2();
p.show();c1.show();c2.show();
System.out.println(c1 instanceof Child1);
System.out.println(c1 instanceof Child2);
System.out.println(c2 instanceof Child1);
System.out.println(c2 instanceof Child2);

}

}
class Parent{
String name = "P";
public void show(){
System.out.println("Parent");
}
}
class Child1 extends Parent{
String name = "C1";
public void show(){
System.out.println("Child1");