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

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

  • 相关阅读:
    Adobe 软件防止联网激活更改Hosts文件
    Spark 共享变量之——Accumulator(累加器)
    AccumulatorV2不生效的问题排查
    RDD的Cache、Persist、Checkpoint的区别和StorageLevel存储级别划分
    2、Spark Core职责之初始化(1)——SparkContext
    1、Spark Core所处位置和主要职责
    Spark作业提交至Yarn上执行的 一个异常
    Swagger2在DBA Service中生成RESTful API的实践
    docker image换包步骤
    GitLab私服在Ubuntu上搭建总结
  • 原文地址:https://www.cnblogs.com/CocoonFan/p/2943668.html
Copyright © 2011-2022 走看看