zoukankan      html  css  js  c++  java
  • 《疯狂Java讲义精粹》读书笔记3 instanceof 运算符

    ----------------《疯狂Java讲义精粹》读书笔记3-------------------

    用法:

      (类型变量 instanceof 类|接口)

    作用:

      instanceof 操作符用于判断前面的对象是否是后面的类,或者其子类、实现类的实例。如果是则返回true 否则就返回false。

    注意:

      · instanceof前面的操作数的编译时类型要么与后面的类相同,要么与后面的类具有父子继承关系否则会引发编译错误

    一个简单的例子:

    /**
     * instanceof 运算符
     * @author Administrator
     *
     */
    
    public class TestInstanceof {
        public static void main(String[] args) {
            //声明hello 时使用Object类,则hello的编译类型是Object
            //Object类是所有类的父类,但hello的实际类型是String
            Object hello = "Hello";
            
            //String是Object的子类可以进行instanceof运算,返回true
            System.out.println("字符串是否为object类的实例:"
                    + (hello instanceof Object));
            
            //true
            System.out.println("字符串是否为String的实例:"
                    + (hello instanceof String));
            
            //false
            System.out.println("字符串是否为Math类的实例:"
                    + (hello instanceof Math));
            
            //String实现了Comparable接口,所以返回true
            System.out.println("字符串是否为Comparable类的实例:"
                    +(hello instanceof Comparable));
            
            /**
             * String 既不是Math类,也不是Math类的父类,故下面代码编译错误
             */
            //String a = "hello";
            //System.out.println("字符串是否为Math类的实例:"
            //        + (a instanceof Math));
            
        }
    }

    运行结果:

    字符串是否为object类的实例:true
    字符串是否为String的实例:true
    字符串是否为Math类的实例:false
    字符串是否为Comparable类的实例:true

      通常在进行强制类型转换之前,先判断前一个对象是不是后一个对象的实例,是否可以成功转换,从而保证代码的健壮性。

  • 相关阅读:
    [转]在C#中使用异步Socket编程实现TCP网络服务的C/S的通讯构架(一)
    Ubuntu操作系统安装使用教程 转载
    ArcInfo和MapInfo的比较 转 http://www.cnblogs.com/njnudt/archive/2007/07/18/821974.html
    jxl导出excel
    flex 图表
    telnet/ssh基本知识
    flex 判断数据类型的几种方法
    友人记
    16进制颜色表
    Ajax不能提交excel
  • 原文地址:https://www.cnblogs.com/CocoonFan/p/2943668.html
Copyright © 2011-2022 走看看