The Type Comparison Operator instanceof

来源:互联网 发布:java jni 参数 编辑:程序博客网 时间:2024/06/06 02:16

This piece of writing is reprinted from the following URL:

http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html 

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface.

class InstanceofDemo {  public static void main(String[] args) {    Parent obj1 = new Parent();    Parent obj2 = new Child();    System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));    System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));    System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));    System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));    System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));    System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));  }}class Parent{}class Child extends Parent implements MyInterface{}interface MyInterface{}
Output:
obj1 instanceof Parent: trueobj1 instanceof Child: falseobj1 instanceof MyInterface: falseobj2 instanceof Parent: trueobj2 instanceof Child: trueobj2 instanceof MyInterface: true
When using the instanceof operator, keep in mind that null is not an instance of anything.

原创粉丝点击