简体   繁体   中英

In Java, why is instanceof a keyword and not a method?

In Java, why is instanceof a keyword and not a method?

public static void main(String args[]) {
    Simple1 s = new Simple1();  
    System.out.println(s instanceof Simple); // true
}

Well, there is the method Class.isInstance ... but basically it's a lower-level operation which has specific VM support, so it makes sense for it to be an operator. Aside from anything else, there's no real need to obtain the Class reference to make the test - the bytecode can represent the operation more efficiently.

Note that you could make the same case for lots of operators... why do we need arithmetic operators rather than calling int x = Integer.add(y, z); for example? There are benefits both in terms of convenience and performance (the latter of which a smart JIT could remove, of course) to having operators.

"instanceof" is an operator in Java and is used to compare an object to a specified type. It is provided as operator so that you can write clearer expressions.

Also isInstance is method present

  1. instanceof keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.

  2. It's an operator that returns true if the left side of the expression is an instance of the class name on the right side.

The whole purpose to have it is to test the object types before performing any Object specific operations, and being binary makes it real easy. There is a method too, but it is rarely used. For instance, you can use it to write a method that checks to see if two arbitrarily typed objects are assignment-compatible, like:

public boolean areObjectsAssignable(Object left, Object right) {
    return left.getClass().isInstance(right);
} 

Please refer this question for more idea,

Java isInstance vs instanceOf operator

instanceof also checks if the Object inherits the given class So if you have: public class Person extends Human you will get true if you write

Person p = new Person();
if(p instanceof Human)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM