19 关键字:instanceof
instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例。
在java中可以使用instanceof关键字判断一个对象到底是某个类的实例:
对象 instanceof 类 ->返回boolean类型
1 class A{ // 定义类A 2 public void fun1(){ // 定义fun1()方法 3 System.out.println("A --> public void fun1(){}") ; 4 } 5 public void fun2(){ 6 this.fun1() ; // 调用fun1()方法 7 } 8 }; 9 class B extends A{ 10 public void fun1(){ // 此方法被子类覆写了 11 System.out.println("B --> public void fun1(){}") ; 12 } 13 public void fun3(){ 14 System.out.println("B --> public void fun3(){}") ; 15 } 16 }; 17 public class InstanceofDemo01{ 18 public static void main(String asrgs[]){ 19 A a1 = new B() ; // 通过向上转型实例化对象 20 System.out.println("A a1 = new B():" + (a1 instanceof A)) ; 21 System.out.println("A a1 = new B():" + (a1 instanceof B)) ; 22 A a2 = new A() ; // 通过向上转型实例化对象 23 System.out.println("A a2 = new B():" + (a2 instanceof A)) ; 24 System.out.println("A a2 = new B():" + (a2 instanceof B)) ; 25 } 26 };
1 class A{ // 定义类A 2 public void fun1(){ // 定义fun1()方法 3 System.out.println("A --> public void fun1(){}") ; 4 } 5 public void fun2(){ 6 this.fun1() ; // 调用fun1()方法 7 } 8 }; 9 class B extends A{ 10 public void fun1(){ // 此方法被子类覆写了 11 System.out.println("B --> public void fun1(){}") ; 12 } 13 public void fun3(){ 14 System.out.println("B --> public void fun3(){}") ; 15 } 16 }; 17 class C extends A{ 18 public void fun1(){ // 此方法被子类覆写了 19 System.out.println("C --> public void fun1(){}") ; 20 } 21 public void fun5(){ 22 System.out.println("C --> public void fun5(){}") ; 23 } 24 }; 25 public class InstanceofDemo02{ 26 public static void main(String asrgs[]){ 27 fun(new B()) ; 28 fun(new C()) ; 29 } 30 public static void fun(A a){ 31 a.fun1() ; 32 if(a instanceof B){ 33 B b = (B) a ; 34 b.fun3() ; 35 } 36 if(a instanceof C){ 37 C c = (C) a ; 38 c.fun5() ; 39 } 40 } 41 };
public interface IObject { } public class Foo implements IObject{ } public class Test extends Foo{ } public class MultiStateTest { public static void main(String args[]){ test(); } public static void test(){ IObject f=new Test(); if(f instanceof java.lang.Object)System.out.println("true"); if(f instanceof Foo)System.out.println("true"); if(f instanceof Test)System.out.println("true"); if(f instanceof IObject)System.out.println("true"); } }
输出结果:
true true true true
在对象向下转型之前最好使用instanceof关键字进行验证
在开发中一定要注意,对于向下转型最好增加验证,以保证转型是不会发生ClassCastException。
如果现在要增加新的子类,则肯定要修改fun()方法,这样一来程序就失去了灵活性,所以在程序的开发中重点的设计应该放在父类上,只要父类设计的足够合理,则开发肯定会非常的方便。
注意:一个类永远不要去继承一个已经实现好的类。而只能继承抽象类或实现接口。

浙公网安备 33010602011771号