public class ColorPoint{
public static void main(String[] args){
String s = null;
System.out.println(s instanceof String);
ColorPoint cp = (ColorPoint) new Object();
}
}
输出什么?能够编译通过吗
调试发现,可以javac过去,但是java时会输出false,然后抛出异常。
public class ColorPoint{
public static void main(String[] args){
System.out.println(new ColorPoint() instanceof String);
}
}
输出什么?可以编译过去吗?
尝试发现,编译不过去。
import java.util.*;
public class ColorPoint{
<span style="white-space:pre"> </span>public static void main(String[] args){
<span style="white-space:pre"> </span>ColorPoint cp = (ColorPoint) new Point();
<span style="white-space:pre"> </span>}
}
class Point{
}
能编译过去吗?编译不过去。
关于instanceof的几个要求
1、当instanceof做操作数为null时,返回值为false,
2、如果两个操作数都是类,其中一个必须是另一个的子类型
关于类型转换的问题
和instanceof一样,当两个都是类的时候那么其中一个必须是另一个的子类,否则将编译不过去,至于能不能转换,就是运行期的事了。