Java面向对象系列(11)- instanceof和类型转换

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);//编译就报错了

 

类型转换

 

 高转低,强转:((子类名) 引用父类参数名).子类方法

 

低(子)转高(父)时,由于子已经继承了父的所有,所以删去属于自己的后自然而然就可以转化问父类的,因此子类转换为父类,会丢失自己的方法;而父想要转子,则需要重新开辟只属于子的空间,则需用强制转换

小结:

  • 父类引用指向子类的对象
  • 把子类转换为父类,向上转型;
  • 把父类转换为子类,向下转型;强制转化
posted @ 2021-09-21 23:29  葛老头  阅读(121)  评论(0)    收藏  举报