instance操作符
概念
1、x instanceof A:
- 检验x是否为类A的对象,返回值为boolean型
- 就是检验某个对象是不是类A的子类
- 要求x所属的类与类A必须是子类和父类的关系,否则编译错误。
- 如果x属于类A的子类B,x instanceof A值也为true
2、示例
Person p = new Person();
Student s = new Student();
System.out.println(s instanceof Person);//true
System.out.println(p instanceof Person);//true
System.out.println(p instanceof Student);//false
Person e = new Student();
System.out.println(e instanceof Student);//true。e指向new Student的一个实例