When comparing whether a class belongs to the same class instance as another class, we can usually use instanceof and getclass two methods to judge whether the two are equal, but there is a difference between the two in the judgment, the following from the code to see the difference:
[Java]View PlainCopy
- Public class Test
- {
- public static void testinstanceof (Object x)
- {
- System.out.println ("x instanceof Parent:" + (x instanceof parent));
- System.out.println ("x instanceof Child:" + (x instanceof Child));
- System.out.println ("x getclass Parent:" + (x.getclass () = = Parent . Class));
- System.out.println ("x getclass Child:" + (x.getclass () = = Child. ) Class));
- }
- public static void Main (string[] args) {
- Testinstanceof (new Parent ());
- System.out.println ("---------------------------");
- Testinstanceof (new Child ());
- }
- }
- Class Parent {
- }
- Class Child extends Parent {
- }
- /*
- Output:
- X instanceof Parent:true
- X instanceof Child:false
- X GetClass parent:true
- X GetClass Child:false
- ---------------------------
- X instanceof Parent:true
- X instanceof Child:true
- X GetClass Parent:false
- X GetClass child:true
- */
As you can see from the program output, the instanceof type check rule is: Do you belong to this class? Or do you belong to a derived class of that class? The operation of obtaining type information by getclass using = = To check whether it is equal is strictly judged. There is no inheritance consideration;
The difference between Java-----instanceof and GetClass