instanceof关键字
instanceof关键字用于判断对象是否是类或其子类所创建的对象,且instanceof左边显式声明的类型与右边操作元必须是同种类或存在继承关系,也就是说需要位于同一个继承树,否则会编译错误
package com.shifan.oop.demo07;
public class Application {
public static void main(String[] args) {
//Object > Person > Student
//Object > Person > Teacher
//Object > String
Object object = new Student();
//true
System.out.println(object instanceof Student);
//true
System.out.println(object instanceof Person);
//true
System.out.println(object instanceof Object);
//false
System.out.println(object instanceof Teacher);
//false
System.out.println(object instanceof String);
System.out.println("=================================================================");
Person person = new Student();
//true
System.out.println(person instanceof Student);
//true
System.out.println(person instanceof Person);
//true
System.out.println(person instanceof Object);
//false
System.out.println(person instanceof Teacher);
//编译报错:System.out.println(person instanceof String);
System.out.println("=================================================================");
Student student = new Student();
//true
System.out.println(student instanceof Student);
//true
System.out.println(student instanceof Person);
//true
System.out.println(student instanceof Object);
//编译报错:System.out.println(student instanceof Teacher);
//编译报错:System.out.println(student instanceof String);
//类型转换:父——子
// 高 低
Person p = new Student();
//将student1转换为Student类型即可调用Student的方法
Student s = (Student)p;
s.run();
//或者:((Student)p).run();
//子类转换为父类后,可能会丢失一些自己本来的方法,这里person1无法再调用子类的run()方法
//低转高,自动转换
Person person1 = student;
}
}