instanceof和类型转换
2023-03-31 11:01:29 时间
1.Instanceof作用
用来判断两个两个类之间是否存在父子关系 代码及详解如下: Application类代码点击查看代码
package com.Tang.oop.demo06;
public class Application {
public static void main(String[] args) {
//Object > String
//Object > Person > Student
//Object > Person > Teacher
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
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);编译就报错
System.out.println("========================");
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);//编译报错
/*
总结:看编译能否通过主要是看对象左边的类型与instanceof 右边的类是否有父子关系
看运行结果为true或false主要是看对象所指向的引用(右边的类)与instanceof右边的类是否存在父子关系
*/
}
}
2.强制转换
Application类代码
点击查看代码
package com.Tang.oop.demo06;
public class Application {
public static void main(String[] args) {
Person person = new Student();
//Person相较于Student类是比较高的类,由高到低需要强制转换
//也就是将person对象强制转化为Student类,才能调用go方法
((Student)person).go();
Student student = new Student();
student.go();
//由低向高转则不需要强转,但是转化为高之后可能就会丢失一些方法
Person person1 = student;
// person1.go();
}
}
点击查看代码
package com.Tang.oop.demo06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
点击查看代码
package com.Tang.oop.demo06;
public class Person {
public void run(){
System.out.println("run");
}
}
相关文章
- 上周热点回顾(2.20-2.26)
- 我做的FFmpeg开源C#封装库Sdcb.FFmpeg
- .Net 6 使用 Consul 实现服务注册与发现 看这篇就够了
- .Net6 使用 Ocelot + Consul 看这篇就够了
- 解密游戏推荐系统的建设之路
- 基于Docker部署Dubbo+Nacos服务
- TikTok 推荐引擎强大的秘密
- 【译】.NET 7 中的性能改进(六)
- 嵌入式Linux—输入子系统
- 衡量算法的性能-时空复杂度分析
- Cobaltstrike —— shellcode分析(一)
- Apache Hudi 负载类Payload使用案例剖析
- Binary &Op是什么
- SnakeYaml的不出网反序列化利用分析
- 自己动手从零写桌面操作系统GrapeOS系列教程——4.GrapeOS开发环境介绍
- 自己动手从零写桌面操作系统GrapeOS系列教程——2.学习写GrapeOS的前提条件
- 推荐一个Dapper扩展CRUD基本操作的开源库
- 纠结的连等赋值
- 为了安装alien,我更新了yum源,结果还是没装上
- 周末折腾了两天,踩了无数个坑,终于把win7装成了centos7