instanceof和类型转换
2021/6/4 10:25:11
本文主要是介绍instanceof和类型转换,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
instanceof:
instanceof 严格来说是Java中的一个双目运算符,用来测试一个对象是否为一个类的实例。
其中 student为一个对象,Class 表示一个类或者一个接口,当 student 为 Class 的对象,或者是其直接或间接子类,或者是其接口的实现类,结果result 都返回 true,否则返回false。
注意:编译器会检查 student 是否能转换成右边的class类型,如果不能转换则直接报错,如果不能确定类型,则通过编译,具体看运行时定。
Application: Person是Student和Teacher的父类
package com.cheng.oop; import com.cheng.oop.pol.Person; import com.cheng.oop.pol.Student; import com.cheng.oop.pol.Teacher; public class Application { public static void main(String[] args) { Teacher teacher = new Teacher();//类实例化 Person person = new Person(); Student student = new Student(); System.out.println(teacher instanceof Person);//true // System.out.println(teacher instanceof Student);//编译直接出错 System.out.println(teacher instanceof Object);//true System.out.println(teacher instanceof Teacher);//true System.out.println("============================"); System.out.println(student instanceof Person);//true System.out.println(student instanceof Student);//true // System.out.println(student instanceof Teacher);//编译直接出错 System.out.println(student instanceof Object);//true System.out.println("================================"); System.out.println(person instanceof Person);//true System.out.println(person instanceof Object);//true System.out.println(person instanceof Student);//false System.out.println(person instanceof Teacher);//false // System.out.println(person instanceof String);//编译出错 System.out.println("============================"); } }
类型之间的转换:
Application:
package com.cheng.oop; import com.cheng.oop.pol.Person; import com.cheng.oop.pol.Student; import com.cheng.oop.pol.Teacher; public class Application { public static void main(String[] args) { //类型之间的转换 : 父子 //高转低需强转 低转高则不需要 //父类 > 子类 Person person = new Teacher();//Person类 Student student = (Student) person;//将Person类强制转换为Student 高转低 Student是Person的子类 student.read();//强制转换后就可以使用read方法 //还可以一句话完成如下: ((Teacher) person).read();//意思是将person强制转换为Teacher类后调用read方法 } }
Teacher:
package com.cheng.oop.pol; public class Teacher extends Person { public void read(){ System.out.println("Teacher.read"); } }
Student:
package com.cheng.oop.pol; public class Student extends Person { public void read(){ System.out.println("Student.read"); } }
此转换可以方便方法的调用,减少重复的代码。
这篇关于instanceof和类型转换的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04el-table 开启定时器下,表格的选中状态会消失是什么原因-icode9专业技术文章分享
- 2024-10-03如何安装和初始化飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03如何安装 App 并连接到飞牛 NAS?-icode9专业技术文章分享
- 2024-10-03如何安装飞牛 TV 并连接到影视服务器?-icode9专业技术文章分享
- 2024-10-03如何在PVE和ESXI上安装飞牛私有云 fnOS?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS安装系统异常情况处理-icode9专业技术文章分享
- 2024-10-03飞牛NAS如何创建存储空间?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS硬盘会自动休眠吗?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何安装飞牛影视和创建媒体库?-icode9专业技术文章分享
- 2024-10-03fnOS国产最强NAS如何为家人朋友开通影视账号?-icode9专业技术文章分享