zoukankan      html  css  js  c++  java
  • JAVA的instanceOf什么时候用

    我个人理解的一个应用场合就是,当你拿到一个对象的引用时(例如参数),你可能需要判断这个引用真正指向的类。所以你需要从该类继承树的最底层开始,使用instanceof操作符判断,第一个结果为true的类即为引用真正指向的类。
    例如下面的例子:
    class Person{} 
    class Student extends Person{}
     class Postgraduate extends Student{} 
    class Animal{}  
    public class InstanceofTester 
    {  
    public static void main(String[] args)
     {
       instanceofTest(new Student());  
    }
      public static void instanceofTest(Person p)
    {
       // 判断p的真正类型 
      if (p instanceof Postgraduate)
    { 
       System.out.println("p是类Postgraduate的实例");   
    }
     else if(p instanceof Student)
    {
        System.out.println("p是类Student的实例");   
    }
     else if(p instanceof Person)
    {
        System.out.println("p是类Person的实例");  
     }
     else if(p instanceof Object) 
    {
        System.out.println("p是类Object的实例");   
    }
       /*if(p instanceof Animal)
    {
    //此错编译错误,所以做注释   
     System.out.println("p是类Animal的实例");   
    }*/  
    } 
    }

    这个程序的输出结果是:p是类Student的实例
    Person类所在的继承树是:Object<--Person<--Student<--Postgraduate。
    这个例子中还加入一个Animal类,它不是在Person类的继承树中,所以不能作为instanceof的右操作数。
  • 相关阅读:
    图论
    利益相关者系统描述
    问题账户需求分析
    2018年春季个人阅读计划
    软件需求分析阅读笔记
    寒假社会实践报告
    敏捷软件需求阅读笔记03
    微信小程序一笔记账开发进度五
    微信小程序一笔记账开发进度四
    微信小程序一笔记账开发进度三
  • 原文地址:https://www.cnblogs.com/fangchongyan/p/5044188.html
Copyright © 2011-2022 走看看