Further understanding of the Java instanceof keyword

  • 2020-04-01 03:42:39
  • OfStack

Instanceof is a binary operator in Java, and ==, > , < It's the same kind of thing. Because it is composed of letters, it is also a reserved keyword for Java. Its purpose is to test whether the object to its left is an instance of the class to its right, returning data of type Boolean. For 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's pointing to is an instance of the Object class, which is obviously true, so return true, which is the value of isObject to true.
Instanceof has some USES. For example, we wrote a billing system with three classes:


    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 takes an object of type Bill and calculates the amount. Assume that the two Bill calculation methods are different, and the Bill object passed in May be either of the two, so use instanceof to judge:


public double calculate(Bill bill) {
    if (bill instanceof PhoneBill) {
        //Calculate the phone bill
    }
    if (bill instanceof GasBill) {
        //Calculate the gas bill
    }
    ...
}

This allows you to work with two seed classes in one method.

However, this approach is generally considered to be a failure to take advantage of polymorphism in object orientation. In fact, the above function requires method overloading can be fully implemented, which is the way to become object-oriented, to avoid going back to structured programming mode. As long as the two names and return values are the same, it is ok to accept different methods with different parameter types:


public double calculate(PhoneBill bill) {
    //Calculate the phone bill
}
public double calculate(GasBill bill) {
    //Calculate the gas bill
}


Related articles: