java基础之instanceof的用法详解

时间:2023-01-30 17:06:20

转载:http://09572.iteye.com/blog/1562277

instanceof 
Java代码  java基础之instanceof的用法详解
  1. interface A{  
  2.       
  3. }  
  4. class B implements A{  
  5.        
  6. }  
  7. class C extends B{  
  8.        
  9. }  
  10. public class Iinstanceof {  
  11.   
  12.     public static void main(String[] args) {  
  13.         A ab=new B();  
  14.         A ac=new C();  
  15.         B bc=new C();  
  16.         B bb=new B();  
  17.         C cc=new C();  
  18.         //对象实现一个接口,用这个对象和这个接口进行instanceof判断,都为true。  
  19.         System.out.println("ab instanceof A="+(ab instanceof A));  
  20.         System.out.println("ac instanceof A="+(ac instanceof A));  
  21.         System.out.println("bc instanceof A="+(bc instanceof A));  
  22.         System.out.println("bb instanceof A="+(bb instanceof A));  
  23.         System.out.println("cc instanceof A="+(cc instanceof A));  
  24.         //对象和父类进行instanceof判断,都为true  
  25.         System.out.println("ab instanceof B="+(ab instanceof B));  
  26.         System.out.println("ac instanceof B="+(ac instanceof B));  
  27.         System.out.println("bc instanceof B="+(bc instanceof B));  
  28.         System.out.println("bb instanceof B="+(bb instanceof B));  
  29.         System.out.println("cc instanceof B="+(cc instanceof B));  
  30.         //对象和他的子类进行instanceof判断为false  
  31.         System.out.println("ab instanceof C="+(ab instanceof C));  
  32.         System.out.println("ac instanceof C="+(ac instanceof C));  
  33.         System.out.println("bc instanceof C="+(bc instanceof C));  
  34.         System.out.println("bb instanceof C="+(bb instanceof C));  
  35.         System.out.println("cc instanceof C="+(cc instanceof C));  
  36.     }  
  37. }  


程序输出:
ab instanceof A=true
ac instanceof A=true
bc instanceof A=true
bb instanceof A=true
cc instanceof A=true
ab instanceof B=true
ac instanceof B=true
bc instanceof B=true
bb instanceof B=true
cc instanceof B=true
ab instanceof C=false
ac instanceof C=true
bc instanceof C=true
bb instanceof C=false
cc instanceof C=true