instanceof运算符用法
运算符是双目运算符,左面的操作元是一个对象,右面是一个类.当左面的对象是右面的类创建的对象时,该运算符运算的结果是true,否则是false
说明:
(1)一个类的实例包括本身的实例,以及所有直接或间接子类的实例
(2)instanceof左边操作元显式声明的类型与右边操作元必须是同种类或右边是左边父类的继承关系,
(3)不同的继承关系下,编译出错
1 class Person { 2 } 3 4 class Student extends Person { 5 } 6 7 class Postgraduate extends Student { 8 } 9 10 class Animal { 11 } 12 13 public class Ex_instanceOf { 14 public static void main(String[] args) { 15 instanceofTest(new Student()); 16 }
* 这个程序的输出结果是:p是类Student的实例
*
* Person类所在的继承树是:Object<–Person<–Student<–Postgraduate。
*
* 这个例子中还加入一个Animal类,它不是在Person类的继承树中,所以不能作为instanceof的右操作数。
*
* @param p
1 public static void instanceofTest(Person p) { 2 // p 和 Animal类型不一样,彼此之间没有继承关系,编译会出错 3 // 提示错误:Incompatible conditional operand types Person and Animal 4 // if(p instanceof Animal){ 5 // System.out.println("p是类Animal的实例"); 6 // } 7 //下面代码的除了第一行都会输出 8 if (p instanceof Postgraduate) System.out.println("p是类Postgraduate的实例"); 9 if (p instanceof Person) System.out.println("p是类Person的实例"); 10 if (p instanceof Student) System.out.println("p是类Student的实例"); 11 if (p instanceof Object) System.out.println("p是类Object的实例"); 12 13 } 14 }
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 }
程序输出:
1 ab instanceof A=true 2 ac instanceof A=true 3 bc instanceof A=true 4 bb instanceof A=true 5 cc instanceof A=true 6 ab instanceof B=true 7 ac instanceof B=true 8 bc instanceof B=true 9 bb instanceof B=true 10 cc instanceof B=true 11 ab instanceof C=false 12 ac instanceof C=true 13 bc instanceof C=true 14 bb instanceof C=false 15 cc instanceof C=true
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/11897.html