- 关键点都在代码注释中
package oop.demo06;
public class Application {
public static void main(String[] args) {
//左侧的实际类型决定了编译是否成功,即左侧的实际类型用于判断一个实例在哪条继承线上
//右侧的指向类型决定了返回结果,即右侧的指向类型是判断一个实例在一个确定的继承线中是否有继承关系
//通式:X instanceof Y //能不能编译通过看X的实际类型
//object > string
//object > person > student
//object > person > teacher
Object 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); //false
System.out.println( student instanceof String); //false
System.out.println("==========================");
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); //编译报错
System.out.println("=========================");
Student student1 = new Student();
System.out.println( student1 instanceof Student); //true
System.out.println( student1 instanceof Person); //true
System.out.println( student1 instanceof Object); //true
//System.out.println( student1 instanceof Teacher); //编译报错
//=============================================================
//类型之间的转换:基本类型转换满足高低
//这里说的转换时
//高 低
Person student2 = new Student();
//子类转换为父类可能丢失一些本来的方法
//student2.eat(); 无法执行,因为Person类中没有eat方法
//将这个转换为student就可以使用student类型的方法,即强行转化成Student类
((Student)student2).eat();
/*
1.必须是父类引用指向子类
2.把子类转换为父类是向上转型,可能会丢失一些方法
3.把父类转换为子类是向下转型,需要强制转换
4.方便了方法的调用
*/
}
}
//结果
true
true
true
false
false
==========================
true
true
true
false
=========================
true
true
true
eat