首页
找靠谱产品
找解决方案
找靠谱公司
找案例
找对的人
专家智库
悬赏任务
SAAS
ToB门户
了解全球最新的ToB事件
论坛
潜水/灌水快乐,沉淀知识,认识更多同行。
ToB圈子
加入IT圈,遇到更多同好之人。
微博
Follow
记录
Doing
博客
Blog
文库
业界最专业的IT文库,上传资料也可以赚钱
下载
分享
Share
排行榜
Ranklist
相册
Album
应用中心
qidao123.com技术社区-IT企服评测·应用市场
»
论坛
›
软件与程序人生
›
后端开发
›
Java
›
instanceof和类型转换
返回列表
发新帖
instanceof和类型转换
[复制链接]
发表于 2022-8-25 05:05:20
|
显示全部楼层
|
阅读模式
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要
登录
才可以下载或查看,没有账号?
立即注册
×
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右边的类是否存在父子关系
*/
}
}
复制代码
此时Student和Teacher类只是都继承了Person类所以并没有什么代码,就不在分别展示
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();
}
}
复制代码
Student类代码
点击查看代码
package com.Tang.oop.demo06;
public class Student extends Person{
public void go(){
System.out.println("go");
}
}
复制代码
Person类代码
点击查看代码
package com.Tang.oop.demo06;
public class Person {
public void run(){
System.out.println("run");
}
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
继续阅读请点击广告
回复
使用道具
举报
返回列表
浏览过的版块
人工智能
钜形不锈钢水箱
+ 我要发帖
×
登录参与点评抽奖,加入IT实名职场社区
去登录
微信订阅号
微信服务号
微信客服(加群)
H5
小程序
快速回复
返回顶部
返回列表