zoukankan      html  css  js  c++  java
  • 《Java基础知识》Java instanceof 运算符

    java多态性带来一个问题,就是如何判断一个变量所实际引用对象的类型。这里java帮我们引入了 instanceof 运算符。

     instanceof运算符用来判断一个变量的所引用对象的实际类型,注意是它引用的对象类型,不是变了类型。

    请看下面的代码:

    public class People {
    }
    public class Teacher extends People {
    }
    public class President extends Teacher {
    }
    public final class Demo {
        public static void main(String[] args){
            People obj = new People();
            if(obj instanceof Object){
                System.out.println("我是一个对象");
            }
            if(obj instanceof People){
                System.out.println("我是一个人");
            }
            if(obj instanceof Teacher){
                System.out.println("我是一名教师");
            }
            if(obj instanceof President){
                System.out.println("我是一名校长");
            }
    
            System.out.println(" --------------------------------------------- ");
    
            obj = new Teacher();
            if(obj instanceof Object){
                System.out.println("我是一个对象");
            }
            if(obj instanceof People){
                System.out.println("我是一个人");
            }
            if(obj instanceof Teacher){
                System.out.println("我是一名教师");
            }
            if(obj instanceof President){
                System.out.println("我是一名校长");
            }
        }
    }

    运行结果:

    可以看出,如果变量引用的是当前类或它的子类的实例,instanceof 返回 true ,否则返回false。

    This moment will nap, you will have a dream; But this moment study,you will interpret a dream.
  • 相关阅读:
    Count and Say
    Valid Sudoku
    Find First and Last Position of Element in Sorted Array
    Search in Rotated Sorted Array
    Longest Valid Parentheses
    web前端中文教程库
    三代基因组拼接软件--Falcon篇
    使用ThreadPoolExecutor并行执行独立的单线程任务
    python中的计时器:timeit
    Python教程
  • 原文地址:https://www.cnblogs.com/jssj/p/11366089.html
Copyright © 2011-2022 走看看