java instanceof method

Basic usage

null instanceof Object   false

null instanceof any class is false;
the corresponding class or parent class of any instance instanceof is true;

The basic data type instanceof Object will report an error when compiling (such as int a; a instanceof Object cannot be compiled), because the basic data type is not an instance of any class

The difference between instanceof and getClass

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 can be seen from the program output, the type checking rules of instanceof are: do you belong to this class? Or do you belong to a derived class of that class? Obtaining type information through getClass and using == to check for equality is a strict judgment. There will be no inheritance considerations



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325386797&siteId=291194637