In Java, why exactly an instance of a keyword, and not a method?

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

 public static void main(String args[]) { Simple1 s = new Simple1(); System.out.println(s instanceof Simple); // true } 
+7
java instanceof
source share
4 answers

Well, there is a Class.isInstance method ... but basically it is a lower-level operation that has some VM support, so it makes sense for it to be an operator. Among other things, there is no real need to get a Class link for the test — bytecode can represent the operation more efficiently.

Please note that you can do the same case for a large number of operators ... why we need arithmetic operators, and not a call int x = Integer.add(y, z); eg? There are advantages in terms of both convenience and performance (the latter of which, of course, can remove smart JIT) with carriers.

+13
source share

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

Also isInstance method is present

+2
source share
  • instanceof keyword is a binary operator used to check if an object (instance) is a subtype of this type.

  • This is a statement that returns true if the left side of the expression is an instance of the class name on the right side.

The goal is to check the types of objects before performing any operations specific to the object, and be binary , which makes it very simple. There is also a method, but it is rarely used. For example, you can use it to write a method that checks if two randomly typed objects are compatible, for example:

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

Please refer to this question for an additional idea,

Java operator isInstance vs instanceOf

0
source share

instanceof also checks whether Object inherits this class. Therefore, if you have: public class Person extends Human , you will get true if you write

 Person p = new Person(); if(p instanceof Human) 
0
source share

All Articles