instanceof
- 先看引用类型的类和instanceof比较的类有没有父子关系,有则可以编译,IDEA不报错
- new一个对象,对象new所在的类和instanceof比较的类有没有父子关系,有则为True,无则为Fals
- 即编译看左边,运行结果True还是False看右边
例子关系
//Object > String
//Object > Person > Teacher
//Object > Person > Student
场景一
package demo01;public class Application {
public static void main(String[] args) {
//Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object = new Student(); System.out.println(object instanceof Student);//True
System.out.println(object instanceof Person);//True
System.out.println(object instanceof Object);//True
System.out.println(object instanceof Teacher);//False
System.out.println(object instanceof String);//False }
}
场景二
Person person = new Student();
System.out.println(person instanceof Student);//True
System.out.println(person instanceof Person);//True
System.out.println(person instanceof Object);//True
System.out.println(person instanceof Teacher);//False
System.out.println(person instanceof String);//编译就报错了
场景三
Student student = new Student();
System.out.println(student instanceof Student);//True
System.out.println(student instanceof Person);//True
System.out.println(student instanceof Object);//True
System.out.println(student instanceof Teacher);//编译就报错了
System.out.println(student instanceof String);//编译就报错了
类型转换
低(子)转高(父)时,由于子已经继承了父的所有,所以删去属于自己的后自然而然就可以转化问父类的,因此子类转换为父类,会丢失自己的方法;而父想要转子,则需要重新开辟只属于子的空间,则需用强制转换
小结:
- 父类引用指向子类的对象
- 把子类转换为父类,向上转型;
- 把父类转换为子类,向下转型;强制转化