Instanceof和类型转换

instanceof和类型转换

instanceof

// Object > Person > Student
// Object > String
public class Application {
    public static void main(String[] args) {
        Person s1 = new Student();
        Student s2 = new Student();
        Object s3 = new Student();
        System.out.println(s1 instanceof Student); //true
        System.out.println(s2 instanceof Student);//true
        System.out.println(s1 instanceof Person);//true
        System.out.println(s2 instanceof Person);//true
        System.out.println(s1 instanceof Object);//true
        System.out.println(s2 instanceof Object);//true
        //System.out.println(s2 instanceof String);报错
        System.out.println(s3 instanceof String); //不报错 false
        System.out.println(s3 instanceof Student);//true
    }
}

总结;

  1. a instanceof b a是b子类或本身的对象则结果为true 此时与引用类型无关
  2. 但是上例中s2和s3去比较String类时,由于s2的引用类型Student和String类不构成任何关系,则编译报错,而s3的引用类型是Object类,是String的父类,所以编译通过。即:编译看左边。而在运行的时候,看的是右边,即对象的类型,s3对象类型是Student和String没有父子关系,所以是false。即:运行看右边。

类型转换

  1. 父亲引用指向子类的对象 (其实就是一种类型的转换) 没有类似Student s1 = new Person();会直接报错
  2. 把子类转换为父类,向上转型
  3. 把父类转换为子类,向下转型:强制转换
  4. 方便方法的调用,减少重复的代码
posted @ 2021-02-24 14:59  Asstrong  阅读(81)  评论(0)    收藏  举报