Instanceof is a two-dollar operator (operator) of Java and PHP, and ==,>,< is the same kind of thing. Because it is made up of letters, it is also a reserved keyword for java. Its function is to determine whether its left object is an instance of its right class and returns a Boolean type of data. Can be used to determine whether an instance of a subclass in an inheritance is an implementation of a parent class. Equivalent to the IS operator in C #. The instanceof operator in Java is used to indicate at run time whether an object is an instance of a particular class. Instanceof Indicates whether this object is an instance of this particular class or its subclasses by returning a Boolean value.
Use of instanceof
One
For example, we wrote a system for handling bills with three classes: public class Bill {//omit Details}public class PhoneBill extends Bill {//omit Details}public class Gasbill Exten DS 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 judge: public double calculate (Bill instanceof PhoneBill) {//Calculate phone Bill}if (Bill instanceof Gasbill) {//Calculate gas bill} ...} 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 programming should be done, 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: public double calculate (PhoneBill Bill) {//Calculate phone bill}public double calculate (gasbill Bill) {//Calculate gas bill} Therefore, the use of instanceof in most cases is not recommended, should take advantage of polymorphism. Ii. coercion of object types for example: Inheritance relationship class Manager extends Employee----------------------------------------------------------public void DoSomething (Employee e) {if (e instanceof manager) {Manager m = (manager) e;}}
Instanceof in Java