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 in java. Its role is to test whether the object on its left is an instance of its right class, and returns a Boolean type of data. As an example:
Copy Code code 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 it points to an instance of the object class, which, obviously, is true, so return true, that is, the IsObject value is true.
Instanceof is of some use. For example, we wrote a billing system with three classes:
Copy Code code 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 that accepts a bill type object and calculates the amount. Suppose the two bills are calculated differently, and the incoming Bill object may be either of two, so use instanceof to determine:
Copy Code code as follows:
Public double Calculate (Bill Bill) {
if (Bill instanceof Phonebill) {
Calculate phone bills
}
if (Bill instanceof Gasbill) {
Calculate gas bill
}
...
}
This allows you to handle two of seed classes in one way.
However, this approach is often considered to be a failure to take advantage of the object-oriented polymorphism. In fact, the above features require method overload can be fully implemented, this is an object-oriented approach should be to avoid the return to structured programming mode. As long as two names and return values are the same, methods that accept different parameter types are available:
Copy Code code as follows:
Public double Calculate (Phonebill bill) {
Calculate phone bills
}
Public double Calculate (Gasbill bill) {
Calculate gas bill
}