10.11 instanceof关键字

这个关键字是用来识别类型的,实际上它应该算做一个运算符,它的语法是这样的:
对象a instanceof 类B
判断对象a是不是类型B的对象,结果返回true或者false
下面我们来看看具体例子
public class Rectangle{
    protected double length;
    protected double height;
    public double sqr(){
        return length*height;
    }
    public double cc(){
        return 2*(length+height);
    }
}
public class Square extends Rectangle{
    public Square(double length){
        this.height=length;
        this.length=length;
    }
}
public static void main(String[]args){
    Rectangle s=new Square(4);
    System.out.println(s instanceof Square);
    System.out.println(s instanceof Rectangle);
}
最后的main函数运行,会打印两个true。因为s是Square对象,也是Rectangle对象。这里的类型是不能随便写的,否则是语法错误。例如上面的Square换成String,马上就会有语法错误。
那么这个instanceof用在哪里呢?主要是用在继承体系的类型判断
例如s声明类型是Rectangle,s的具体类型有可能是Rectangle的任何子类,也可能就是Rectangle类本身。例如上面的main函数变成这样:
public static void main(String[]args){
    Rectangle s=new Rectangle();
    System.out.println(s instanceof Square);
    System.out.println(s instanceof Rectangle);
}
这时候就只会打印一个true了,s instanceof Square的返回结果就是false,因为s具体类型是Rectangle,它不是Square。