The instanceof Keyword

来源:互联网 发布:总后勤部职工数据库 编辑:程序博客网 时间:2024/05/18 02:45

http://www.java2s.com/Tutorial/Java/0060__Operators/TheinstanceofKeyword.htm


The instanceof keyword can be used to test if an object is of a specified type.

public class MainClass {  public static void main(String[] a) {    String s = "Hello";    if (s instanceof java.lang.String) {      System.out.println("is a String");    }  }}

Output: is a String.


However, applying instanceof on a null reference variable returns false. 

public class MainClass {  public static void main(String[] a) {    String s = null;    if (s instanceof java.lang.String) {      System.out.println("true");    } else {      System.out.println("false");    }  }}
output: false


class Parent {  public Parent() {  }}class Child extends Parent {  public Child() {    super();  }}public class MainClass {  public static void main(String[] a) {    Parent p = new Child();    if (p instanceof Parent) {      System.out.println("true");    }  }}
output: true
原创粉丝点击