做了下面2个测试:
(1)
Integer n = new Integer(3);
boolean bo3 = n instanceof Integer;
System.out.println(bo3);
这样打印出来是true(2)
Integer n = new Integer(3);
boolean bo3 = n instanceof String;
System.out.println(bo3);
这样,我认为应该打印出false
但是编译的时候报错了:
Incompatible conditional operand types Integer and String
说Integer 和 String有矛盾!
但是我认为打印出来应该是false才对!不知道boolean bo3 = n instanceof String;这句话为什么编译会提示那样的错误?
谢谢!
(1)
Integer n = new Integer(3);
boolean bo3 = n instanceof Integer;
System.out.println(bo3);
这样打印出来是true(2)
Integer n = new Integer(3);
boolean bo3 = n instanceof String;
System.out.println(bo3);
这样,我认为应该打印出false
但是编译的时候报错了:
Incompatible conditional operand types Integer and String
说Integer 和 String有矛盾!
但是我认为打印出来应该是false才对!不知道boolean bo3 = n instanceof String;这句话为什么编译会提示那样的错误?
谢谢!
解决方案 »
- 关于java socket短时间内发送大量消息的问题
- JAVA程序的规范写法
- Java文本框中实现鼠标数字的滚动
- 为什么我的web.xml里面用不了<filter>这个标识呢?
- j2eesdk 1.3跟j2eesdk 1.4的区别?在线等喔!(100分!!!!)
- 请问怎么用java写bin文件阿?
- == 和 equals() 的不同
- 有谁在看Robert Eckstein & Mare Loy & Dave Wood写的 Java Swing (O'REILLY)
- tomcat高手入内(在线等等)
- 类装载器的问题,请大虾赐教
- 如何在canvas上添加光标
- 在java中怎样保存图像?分不够再加!
所以应该返回false才对!
我不知道instanceof的用法了!!谁能说说?
那像楼上说的,不是永远返回true吗?不是很明白instanceof怎么用了?
1.不可能
Integer -->String
2.一定可以
String --->Object
3.有可能(运行是才知道)
Object ---->String上面的类型都是编译时类型!前两者都是编译时就知道,所有我们不会用它
但是编译器好像只阻止了第一种情况,而没有阻止第二种情况,就相当域我们写if(1==1) 也不会出错.
如果在return 语句后还有代码,一般编译不错,但是如果改为
if(ture) return; 就可以编译通过了.
好像不是这样吧?
"就是编译期检查右值"
不是很明白?右值?
操作符当然不是随便用的, a instanceof B后的类名B,必须与a指向的对象有继承关系。因为向上造型是自动的,不需要检查,而向下造型必须在“运行时”检查。
public static void main(String args[]) {
B bb = new A ();
B bbbb = new B();
if (bb instanceof A){
A a= (A)bb;
System.out.println("bb instanceof A");
a.doSth();
} //A a= (A)bbbb; //运行时错误
if (bbbb instanceof A){
A a= (A)bbbb;
a.doSth();
}else System.out.println("bbbb ! instanceof A");
}
void doSth(){System.out.println("hi");}
}class B{}
boolean bo3 = n instanceof String;
System.out.println(bo3);
这样才可以通过,因为原来的n是一个Integer对象,绝对不可能是一个String,编译器直接否定了你的判断