您的位置:首页 > 其它

instanceof and getClass()

2016-01-09 16:29 162 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  inheritance