instanceof 和类型转换

2023-03-10,,

instanceof类型转换

instanceof

判断a 和 B 类型是否相似
公式 System.out.println(a instanceof B); //true / false
编译是否通过? (a的引用类型和B类型是否存在父子关系
编译通过之后结果true还是false(a指向的实际类型是否是B的子类型

//判断a 和 B 类型是否相似
//公式 System.out.println(a instanceof B); //true / false
//编译是否通过? (a的引用类型和B类型是否存在父子关系)
//编译通过之后结果true还是false(a指向的实际类型是否是B的子类型) //Object > String
//Object > Person > Teacher
//Object类 > Person类 > Student类 //引用类型为Object的引用变量object 指向的实际类型为 Student类型
Object object = new Student();
//判断引用变量object是否是Student类型 true
System.out.println(object instanceof Student); 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 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);
//编译就报错 Person类 和String类是同级下的,无关,没有转换关系 System.out.println("-----------------------------------");
Student student = new Student();
System.out.println(student instanceof Student);
System.out.println(student instanceof Person);
System.out.println(student instanceof Object);
//System.out.println(student instanceof Teacher);
//编译就报错 Student(指引用类型) 和 Teacher无关
//System.out.println(student instanceof String);
//编译就报错 Student 和 String无关

类型转换

        //类型转换
//之前学的是基本类型转换 低到高,自动转(byte short char int long float double), 高到低(64 32 16 8) 强制转换
//现在学的是引用类型转换 父类(高)跟子类(低)转换 System.out.println("================类型之间的转换=============");
//一
//高 低 低---》高 自动转,不用强制转换
Person per1 = new Student();
//student.go();// 不能调用 此时Person中只有 run() ,Student中有go() 且继承run()
//那么如何让对象student 调用go()呢 ? 将对象student的类型(目前是Person类型)转换为Student类型,就可以使用Student类型的方法了
//Person类型 转 Student类型 高转低 强制转 ((Student)per1).go();
Student stu = (Student) per1;
stu.go(); //二 子类转父类 ,可能丢失一些自己本来的方法
Student stu1 = new Student();
//现在引用变量(对象)student 的引用类型为Student 想把它的类型转换为Person类型 低转高自动转 Person per2 = stu1; //默认转 Student类型转换为Person类型
//per2.go;报错
// 此时原来stu1类型为Student类型,转换为Person类型(转换为父类后)后,不能用Student的方法了,子类转父类 ,可能丢失一些自己本来的方法 }
}

注意

/*

    父类的引用指向子类的对象 不能子类的引用指向父类的对象
    把子类转换为父类,向上转型,低转高,自动转,不用强制转换 可能会丢失一些方法
    把父类转换为子类,向下转型,高转低,需要强制转换
    类型转换:方便方法的调用,减少重复的代码,使代码更简洁!
    *

抽象的编程思想: 封装,继承,多态,越来越抽象
*
*/

​ 类型转换可能造成丢失精度或方法

instanceof 和类型转换的相关教程结束。

《instanceof 和类型转换.doc》

下载本文的Word格式文档,以方便收藏与打印。