instanceof is a binary operator in Java, and ==, >, and < are the same type of things. Since it is composed of letters, it is also a reserved keyword in Java. Its function is to test whether the object on its left is an instance of the class on its right and return data of type boolean. For example:
The code copy is as follows:
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 Object class. Obviously, this is true, so we return true, that is, the value of isObject is True.
instanceof has some uses. For example, we wrote a system for handling bills, which has three categories:
The code copy is as follows:
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 to accept an object of type Bill and calculate the amount. Assume that the two bill calculation methods are different, and the incoming Bill object may be either of two, so use instanceof to judge:
The code copy is as follows:
public double calculate(Bill bill) {
if (bill instance of PhoneBill) {
//Calculate the phone bill
}
if (bill instance of GasBill) {
// Calculate the gas bill
}
...
}
This way, two subclasses can be processed in one method.
However, this approach is often considered as a failure to take advantage of object-oriented polymorphisms. In fact, the above functions require that method overloading can be achieved completely. This is the method of object-oriented becoming the right one to avoid returning to the structured programming mode. Just provide two names and return values and accept methods with different parameter types:
The code copy is as follows:
public double calculate(PhoneBill bill) {
//Calculate the phone bill
}
public double calculate(GasBill bill) {
// Calculate the gas bill
}