天天看点

JavaSe面向对象09:instanceof和类型转换(笔记)

视频学习地址

点我跳转ψ(`∇´)ψ

前言

instanceof可以判断两个类之间是否存在继承关系
public class Application {
    public static void main(String[] args) {
        //Object > String
        //Object > Person > Teacher
        //Object > Person > Student

        Object o = new Student();
        System.out.println(o instanceof Student);   //true
        System.out.println(o instanceof Person);    //true
        System.out.println(o instanceof Object);    //true
        System.out.println(o instanceof Teacher);   //false
        System.out.println(o instanceof String);    //false

        Person p = new Student();
        System.out.println(p instanceof Student);   //true
        System.out.println(p instanceof Person);    //true
        System.out.println(p instanceof Object);    //true
        System.out.println(p instanceof Teacher);   //false
        //System.out.println(p instanceof String);    编译报错

        Student s = new Student();
        System.out.println(s instanceof Student);   //true
        System.out.println(s instanceof Person);    //true
        System.out.println(s instanceof Object);    //true
        //System.out.println(s instanceof Teacher);   编译报错
        //System.out.println(s instanceof String);    编译报错
    }
}
           

总结一句话就是编译是否通过看左边的引用类型和被instanceof的类型是否存在继承关系,如果编译通过则看右边的被new的类对象是否存在继承关系,存在为true,反之为false。

类型转换

public class Application {
    public static void main(String[] args) {
        //高           低
        Person p = new Student();
        Student s = (Student) p;    //这个是高转低,需要强制转换
        s.go();                     //可以和上面一步到位写成((Student) p).go();

        //同类型          同类型
        Student s2 = new Student();         
        Person p2 = s2;     //这个是低转高,子类转换为父类,会丢失自己的一些方法
        p2.run();           //可以和上面一步到位写成((Person) s2).run(); 
    }
}
           
public class Person {
    public void run(){
        System.out.println("run");
    }
}

           
public class Student extends Person{
    public void go(){
        System.out.println("go");
    }
}


           

总结

  • 父类引用指向子类的对象
  • 子类转换为父类,向上转型
  • 父类转换为子类,向下转型,需要强制转换
  • 方便方法的调用,减少重复的代码,简洁