Instanceof is a Java two-dollar operator, and ==,>,< is the same kind of stuff. Because it is made up of letters, it is also a reserved keyword for java. Its purpose is to test whether the object on its left is an instance of the class to the right of it, returning a Boolean type of data. As an example:
String s = "I AM an object!";
Boolean IsObject = s instanceof Object;
We declare a String object reference, point to a String object, and then use INSTANCOF to test whether the object it points to is an instance of the objects class, which, obviously, is true, so return true, that is, the value of IsObject is true.
Instanceof has some use. For example, we wrote a system that handles bills, and there are three of these:
public class Bill {//omit details}
public class PhoneBill extends Bill {//omit details}
public class Gasbill extends Bill {//omit details}
There is a method in the handler that accepts an object of type bill and calculates the amount. Suppose the two billing methods are different, and the incoming Bill object may be any of the two, so use instanceof to determine:
Public double Calculate (Bill Bill) {
if (Bill instanceof PhoneBill) {
Calculate phone bills
}
if (Bill instanceof Gasbill) {
Calculate gas bills
}
...
}
This allows the two seed class to be processed in one way.
However, this practice is often thought of as not taking good advantage of the polymorphism in object-oriented. In fact, the above function requires a method overload can be fully implemented, this is an object-oriented approach should be done to avoid back to the structured programming mode. As long as the two names and return values are the same, a different method of accepting the parameter types is available:
Public double Calculate (PhoneBill bill) {
Calculate phone bills
}
Public double Calculate (Gasbill bill) {
Calculate gas bills
}
Therefore, the use of instanceof in most cases is not recommended practice, should make good use of polymorphism.
Android Java instanceof keywords