instanceof and getClass()

instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.
getClass() == … tests whether the types are identical.

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

is a String

However, applying instanceof on a null reference variable returns false. For example, the following if statement 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");
    }
  }

}

false

Since a subclass ‘is a’ type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.

class Parent {
  public Parent() {

  }
}

class Child extends Parent {
  public Child() {
    super();
  }
}

public class MainClass {
  public static void main(String[] a) {

    Child child = new Child();
    if (child instanceof Parent) {
      System.out.println("true");
    }

  }

}

true

你可能感兴趣的:(Core-Java)