Original works, can be reproduced, but please mark the source address: http://www.cnblogs.com/V1haoge/p/8492158.html
The instanceof keyword is the most commonly used keyword in a Java class to implement the Equals method, indicating whether the object on its left is an instance of the right type, where the type on the right can be extended to the inheritance, implementation structure, can be its true type, or the true type of the super type, the Hyper-interface type, and so on.
Instanceof the left side must be an object instance or a null type, otherwise it cannot be compiled.
The right side of the instanceof must be the convertible type of the left object (which can be strongly turned), otherwise it cannot be compiled.
Usage examples:
1 Interfaceifather1{}2 InterfaceISon1extendsifather1{}3 classFather1Implementsifather1{}4 classSon1extendsFather1Implementsison1{}5 Public classInstanceoftest {6 Public Static voidMain (string[] args) {7Father1 Father1 =NewFather1 ();8Son1 Son1 =NewSon1 ();9System.out.println (Son1instanceofIFather1);//1-Super InterfaceTenSystem.out.println (Son1instanceofFather1);//2-Super class OneSystem.out.println (Son1instanceofISon1);//3-Current Class ASystem.out.println (Father1instanceofIFather1);//4-Super Interface -System.out.println (Father1instanceofISon1);//false - } the}
The result of the execution is:
true true true true false
View Code
As shown in the example above: except for the last one, the first four are all true, and the inheritance relationship of the view class is as follows:
As you can see, the Son1 class is the final class, and its object Son1 can instanceof the interfaces and classes above so (IFather1, ISon1, Father1, Son1), and Father1 instance father1 superior only IFather1 interface and this kind of Father1 can instanceof, the rest cannot succeed.
So that we can understand the purpose of instanceof, and finally say its role in equals, let's look at a simple equals implementation (from the Java.lang.String Class):
1 Public Booleanequals (Object anobject) {2 if( This==anobject) {3 return true;4 }5 if(AnObjectinstanceofString) {6String anotherstring =(String) anobject;7 intn =value.length;8 if(n = =anotherString.value.length) {9 CharV1[] =value;Ten CharV2[] =Anotherstring.value; One inti = 0; A while(n--! = 0) { - if(V1[i]! =V2[i]) - return false; thei++; - } - return true; - } + } - return false; +}
The instanceof keyword is clearly used in the 5th exercise to determine whether a given parameter object is an instance of the string class. differs from the GetClass () method, which obtains the actual type of the current object without an inheritance relationship.
1 System.out.println (Son1.getclass ()); 2 System.out.println (Father1.getclass ());
The result is:
class Son1 class Father1
View Code
Reference: Java keyword--instanceof
Java Basic Series--instanceof keywords