Android Java instanceof keyword, androidinstanceof
Instanceof is a binary operator of Java. It is the same class as =, >,<. Because it is composed of letters, it is also a reserved keyword of Java. It is used to test whether the object on the left is an instance of the class on the right of the object and return boolean data. For example:
String s = "I AM an Object! ";
Boolean isObject = s instanceof Object;
We declared a String Object reference, pointing to a String Object, and then using instancof to test whether the Object it points to is an instance of the Object class. Obviously, this is true, so true is returned, that is, the isObject value is True.
Instanceof is useful. For example, we have written a bill processing system, which has three classes:
Public class Bill {// omitting details}
Public class PhoneBill extends Bill {// omitting details}
Public class GasBill extends Bill {// omitting details}
There is a method in the handler that accepts a Bill-type object and calculates the amount. Assume that the two billing methods are different, and the incoming Bill object may be either of them. Therefore, use instanceof to judge:
Public double calculate (Bill bill ){
If (bill instanceof PhoneBill ){
// Calculate the telephone bill
}
If (bill instanceof GasBill ){
// Calculate the gas bill
}
...
}
In this way, two subclass classes can be processed in one way.
However, this approach is generally considered to be failing to take advantage of object-oriented polymorphism. In fact, the above functional requirements can be fully implemented by using method overloading, which is an appropriate approach for object-oriented development and avoids returning to the structured programming mode. You only need to provide two methods with the same name and return value, and accept the methods with different parameter types:
Public double calculate (PhoneBill bill ){
// Calculate the telephone bill
}
Public double calculate (GasBill bill ){
// Calculate the gas bill
}
Therefore, using instanceof is not recommended in most cases, and polymorphism should be well utilized.