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. }   
posted @ 2018-07-31 16:06  buptyuhanwen  阅读(112)  评论(0编辑  收藏  举报