Java Example - Usage of instanceof Keyword

Java 实例Java Examples

instanceof is a binary operator in Java, similar to ==, >, < and other operators.

instanceof is a reserved keyword in Java. Its purpose is to test whether the object on its left is an instance of the class on its right, returning a boolean data type.

The following example creates the displayObjectClass() method to demonstrate the usage of the Java instanceof keyword:

Main.java file code:

/* author by example.com Main.java */ import java.util.ArrayList; import java.util.Vector; public class Main { public static void main(String[] args) { Object testObject = new ArrayList(); displayObjectClass(testObject); } public static void displayObjectClass(Object o) { if (o instanceof Vector) System.out.println("The object is an instance of the java.util.Vector class"); else if (o instanceof ArrayList) System.out.println("The object is an instance of the java.util.ArrayList class"); else System.out.println("The object is" + o.getClass() + "an instance of the class"); } }

The output of the above code is:

对象是 java.util.ArrayList 类的实例

Java 实例Java Examples

Other Extensions