介绍
Java 中的instanceof 运算符是用来指出对象是否是特定类的一个实例,返回值是Boolean
用法:result = object instanceof class
参数:
Result:布尔类型。
Object:必选项。任意对象表达式。
Class: 必选项。任意已定义的对象类。
说明:
如果 object 是 class 的一个实例,则 instanceof 运算符返回 true。
如果 object 不是指定类的一个实例,或者 object 是 null,则返回 false。
如果不存在继承关系下,编译出错
例子
public static void main(String[] args) {
Person p = new Person("l'm person");
Student pp = new Student("l'm student");
Object obj = null;
objectOperation();
testInstance(p, pp, obj);
}
public static void testInstance(Person p,Person pp ,Object obj){
Boolean result;
result = p instanceof Student;
System.out.println("person p instance of student " + result);
result = p instanceof Person;
System.out.println("person p instance of Person " + result);
result = p instanceof Object;
System.out.println("person p instance of Object " + result);
result = p instanceof Exam;
System.out.println("person p instance of Interface Exam " + result);
result = pp instanceof Person;
System.out.println( "student pp instance of Person "+ result);
result = obj instanceof Object;
System.out.println("null object obj instanceof Object " + result);
// 编译出错
// System.out.println(p instanceof System);
}
public static void objectOperation(){
String a = "hello";
String b = "java";
Boolean result;
result = a+b instanceof String;
System.out.println("字符串相加仍是字符串 "+ result);
}
class Person{
String name = null;
public Person(String name) {
this.name = name;
}
public void shout(){
System.out.println(name);
}
}
class Student extends Person implements Exam{
public Student(String name) {
super(name);
}
public void getMathGrade() {}
public void getChineseGrade() {System.out.println("这是我的语文成绩");}
}
输出
字符串相加仍是字符串 true
person p instance of student false
person p instance of Person true
person p instance of Object true
person p instance of Interface Exam false
student pp instance of Person true
null object obj instanceof Object false