• java基础---instanceof


    a instanceof class
    左边必须是子类的实例,同时class也可以是接口,只要对象实现了就行。
     
    1. package myPackage;    
    2. /**  
    3. * instanceof运算符用法  
    4. * 运算符是双目运算符,左面的操作元是一个对象,右面是一个类.当  
    5. * 左面的对象是右面的类创建的对象时,该运算符运算的结果是true,否则是false  
    6. *   
    7. * 说明:(1)一个类的实例包括本身的实例,以及所有直接或间接子类的实例  
    8. * (2)instanceof左边操作元显式声明的类型与右边操作元必须是同种类或右边是左边父类的继承关系,  
    9. * (3)不同的继承关系下,编译出错  
    10. */    
    11. class Person {    
    12. }    
    13. class Student extends Person {    
    14. }    
    15. class Postgraduate extends Student {    
    16. }    
    17. class Animal {    
    18. }    
    19. public class Ex_instanceOf {    
    20. public static void main(String[] args) {    
    21.    instanceofTest(new Student());    
    22. }    
    23. /**  
    24. * 这个程序的输出结果是:p是类Student的实例  
    25. *   
    26. * Person类所在的继承树是:Object<--Person<--Student<--Postgraduate。  
    27. *   
    28. * 这个例子中还加入一个Animal类,它不是在Person类的继承树中,所以不能作为instanceof的右操作数。  
    29. *   
    30. * @param p  
    31. */    
    32. public static void instanceofTest(Person p) {    
    33.    // p 和 Animal类型不一样,彼此之间没有继承关系,编译会出错    
    34.    // 提示错误:Incompatible conditional operand types Person and Animal    
    35.    // if(p instanceof Animal){    
    36.    // System.out.println("p是类Animal的实例");    
    37.    // }    
    38.    //下面代码的除了第一行都会输出    
    39.    if (p instanceof Postgraduate) System.out.println("p是类Postgraduate的实例");    
    40.    if (p instanceof Person) System.out.println("p是类Person的实例");    
    41.    if (p instanceof Student) System.out.println("p是类Student的实例");    
    42.    if (p instanceof Object) System.out.println("p是类Object的实例");    
    43.    
    44. }    
    45. }   
  • 相关阅读:
    [05] EL表达式
    [03-01] JSP自定义标签
    [04] JSP标准动作
    [03] JSP指令
    Fiddler抓包调试前端脚本代码
    《互联网协议入门》思维导图笔记
    Nodejs学习笔记(十)—与MongoDB的交互(mongodb/node-mongodb-native)、MongoDB入门
    Nodejs学习笔记(九)—与Redis的交互(mranney/node_redis)入门
    Nodejs学习笔记(八)—Node.js + Express 实现上传文件功能(felixge/node-formidable)
    Nodejs学习笔记(七)—Node.js + Express 构建网站简单示例
  • 原文地址:https://www.cnblogs.com/buptyuhanwen/p/9396420.html
Copyright © 2020-2023  润新知