Java类型转换之instanceof

/*
 *   引用类型转换
 * 1、向下转型
 * 2、向上转型
 * 3、instanceof运算符,用来检查引用对象的类型
 * 
 */

public class Hey {
    public static void main(String[] args) {
        // 向下转换成功
        Circle c = new Circle();
        Shape s = (Shape)c;
        Shape s2= (Shape)new Circle();
        Circle c2 = (Circle)s2;

        s2 = new Rect();
        // Circle c3 = (Circle) s2; //Rect cannot be cast to Circle // 转换异常

        // 用如下代码测试是否可以转换
        if(testIfCanCast(s2)) {
            Circle c3 = (Circle) s2; //Rect cannot be cast to Circle
        }

    }

    /*
     * test if can cast to Circle
     * */
    private static boolean testIfCanCast(Shape s){
        if(s instanceof Circle) {
            Circle c = (Circle) s; 
            System.out.println("OK");
            return true;
        }else {
            System.out.println("Error, cannot cast to Circle.");
            return false;
        }
    }
}

class Shape{

}

class Circle extends Shape{

}

class Rect extends Shape{

}

你可能感兴趣的:(Java学习笔记)