?? Usually we use the INSTANCEOF keyword to determine whether an object is an instance of the class, recently Bo master saw isinstance keyword, puzzled and instanceof difference, so the degree Niang a bit, the way up a bit posture.
?? There are 3 keywords in Java that determine the relationship between a class and an instance: Instanceof, Isinstance, and IsAssignableFrom.
- Instanceof: Used to determine if an object is an instance of a class
- Isinstance: Used to determine whether an object belongs to an instance of a type
- IsAssignableFrom: Used to determine whether there is a derivation between types
?? After reading the above explanation, is it still in foggy?
?? Here's a detailed explanation.
?? The instanceof operator is used only for object reference variables, checking that the test object on the left is not an instantiation of the right class or interface. If the object being measured is a null value, the test result is always false.
?? The image is described as: self instance or subclass instance Instanceof itself class returns True
Cases:
String s=newString("javaisland"instanceofString//true
?? The class Isinstance (Object obj) method, where obj is the object being tested and returns true if Obj is an instance of the class or interface that called the method. This method is the dynamic equivalent of the instanceof operator.
?? Depicted as: Self class. Class.isinstance (instance of itself or subclass) returns True
Cases:
String s=newString("javaisland");System.out.println(String//true
?? Class IsAssignableFrom (class CLS) method, which returns true if the class or interface calling this method is the same as the classes or interfaces represented by the parameter CLS, or is the parent class of the class or interface that the parameter CLS represents.
?? Depicted as: Own class. Class.isassignablefrom (Own class or subclass. Class) returns True
Cases:
System.out.println(ArrayList.class.isAssignableFrom(Object.class)); //falseSystem.out.println(Object.class.isAssignableFrom(ArrayList.class)); //true
Java determines the relationship between classes and instances