举例:Student和Teacher都继承Person。
package com.zhang.oop.Instanceof;
public class App {
public static void main(String[] args) {
// Object>Person>Student
// Object>Person>Teacher
// Person>String
// System.out.println(X instanceof Y)能不能编译通过?就取决于X与Y之间是否是继承关系。即子类和父类的关系
Object s1 = new Student();
System.out.println(s1 instanceof Object);//true
System.out.println(s1 instanceof Person);//true
System.out.println(s1 instanceof Student);//true
System.out.println(s1 instanceof Teacher);//false
System.out.println(s1 instanceof String);//false
System.out.println("===================================");
Person s2 = new Student();
System.out.println(s2 instanceof Object);//true
System.out.println(s2 instanceof Person);//true
System.out.println(s2 instanceof Student);//true
System.out.println(s2 instanceof Teacher);//false
System.out.println("====================================");
Student s3 = new Student();
System.out.println(s3 instanceof Object);//true
System.out.println(s3 instanceof Person);//true
System.out.println(s3 instanceof Student);//true
}
}
我们可以看到,只有new 的对象和 instanceof 比较的对象有继承关系时才能通过。
还有一种情况 都不在同一条线上 无法比较,如 Student 和 String、Student 和 Teacher。
这会有点,总结一下
能否变异通过看x与y的类,如果存在子父关系或父子关系,则能编译通过。
若x与y不存在父子关系则不能通过如 Student 和 String、Student 和 Teacher。
编译过后T/F看引用指向对象,x指向的对象如果是后面y的子类,即是T反之为F。
类型之间的转化
之前我们在方法重写那遇到过,父类强制调用子类需要转化数据类型。父类为高等类 子类为低等类。
如下图 Student类里有个go();方法Person类中没有。
Person类要调用Student类的方法失败
要想调用成功的把高类型装化为第类型。,
就是说父类用不了子类方法 就是把自己伪装成子类(类型转换)就可以用了。
总结
把子类转换为父类:向上转型,直接转化(低--------->高)。
把父类转换为则子类:向下转型,强制转换(高--------->低)。
和之前的数据类型转换差不多。