Beginners are inevitably a little confused about the role of Java instanceof and GetClass (), the following one by one to explain.
Parent Class A:
class A {}
Sub-Class B:
class extends
Constructing objects
New
New
First, instanceof
Demo One:
instanceof
instanceof
instanceof
instanceof
Analysis ==>
Usage:
English: Result = Object instanceof class
English: result = An Instance object instanceof a class name
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.
Summary: S (object) instanceof T (Class) simply, instanceof is to determine whether the object S is an instance of the T class, or a subclass instance of the T class. Second, GetClass
Demo Two:
1, O1.getclass (). Equals (A.class
2, O1.getclass (). Equals (B.class
3, O2.getclass (). Equals (A.class
4, O2.getclass (). Equals (B.class
The analysis ==>getclass method is defined in JDK1.8 as follows:
/**
* Returns the runtime class of this Object
*/
Public Final native Class<?> getclass ();
Function: Returns the object at the run-time class. GetClass () would be useful if you want to make sure your instance was not a subclass of the class you were comparing with. Three, the difference between instanceof and GetClass 1, the role:
- Instanceof: Used primarily to determine the relationship between objects and classes.
- GetClass: Primarily used to determine the relationship between classes and classes.
Reference: 1, http://www.jb51.net/article/36114.htm
The role of instanceof and GetClass () in Java