Java基础系列--instanceof关键字

原创做品,能够转载,可是请标注出处地址:http://www.cnblogs.com/V1haoge/p/8492158.htmlhtml

  instanceof关键字是在Java类中实现equals方法最常使用的关键字,表示其左边的对象是不是右边类型的实例,这里右边的类型能够扩展到继承、实现结构中,能够是其真实类型,或者真实类型的超类型、超接口类型等。java

  instanceof左边必须是对象实例或者null类型,不然没法经过编译。ide

  instanceof右边必须是左边对象的可转换类型(可强转),不然没法经过编译。this

  使用实例:spa

 1     interface IFather1{}  2     interface ISon1 extends IFather1{}  3     class Father1 implements IFather1{}  4     class Son1 extends Father1 implements ISon1{}  5     public class InstanceofTest {  6         public static void main(String[] args){  7             Father1 father1 = new Father1();  8             Son1 son1 = new Son1();  9             System.out.println(son1 instanceof IFather1);//1-超接口 10             System.out.println(son1 instanceof Father1);//2-超类 11             System.out.println(son1 instanceof ISon1);//3-当前类 12             System.out.println(father1 instanceof IFather1);//4-超接口 13             System.out.println(father1 instanceof ISon1);//false 14  } 15     }

  执行结果为:code

true
true
true
true
false
View Code

  如上实例所示:除了最后一个,前四个所有为true,查看类的继承关系以下:htm

  

  能够明显看到,Son1类是最终的类,其对象son1能够instanceof上面全部的接口和类(IFather一、ISon一、Father一、Son1),而Father1的实例father1上级只有IFather1接口和本类Father1能instanceof,其他均没法成功。对象

  这样咱们就能理解instanceof的用途了,最后说说其在equals中的做用,咱们来看个简单的equals实现(来自java.lang.String类):blog

 1     public boolean equals(Object anObject) {  2         if (this == anObject) {  3             return true;  4  }  5         if (anObject instanceof String) {  6             String anotherString = (String) anObject;  7             int n = value.length;  8             if (n == anotherString.value.length) {  9                 char v1[] = value; 10                 char v2[] = anotherString.value; 11                 int i = 0; 12                 while (n-- != 0) { 13                     if (v1[i] != v2[i]) 14                             return false; 15                     i++; 16  } 17                 return true; 18  } 19  } 20         return false; 21     }

  明显在第5行使用到了instanceof关键字,其目的就是为了判断给定的参数对象是不是String类的实例。区别于getClass()方法,后者获得的是当前对象的实际类型,不带继承关系。继承

1  System.out.println(son1.getClass()); 2         System.out.println(father1.getClass());

  结果为:

class Son1 class Father1
View Code

 

参考:Java关键字——instanceof

相关文章
相关标签/搜索