12.instanceof和类型转换
2024-10-08 05:34:19
Instanceof:
判断一个对象是什么类型的~,可以判断两个类之间是否存在父子关系
package com.oop.demo07; public class Person { public void run(){
System.out.println("run");
} }
package com.oop.demo07; public class Student extends Person { public void go() {
System.out.println("go");
} }
package com.oop.demo07; public class Teacher extends Person{
}
package com.oop; import com.oop.demo07.Person;
import com.oop.demo07.Student;
import com.oop.demo07.Teacher;
public class Application { public static void main(String[] args) { //Object > String
//Object > Person > Teacher
//Object > Person > Student
Object object = new Student(); //System.out.println(X instanceof Y);//能不能编译通过!取决于X和Y之间是否存在父子关系!
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);//编译报错 }
}
类型转换:
package com.oop; import com.oop.demo07.Person;
import com.oop.demo07.Student; public class Application { public static void main(String[] args) {
//类型之间的转换:基本类型转换 父 子 //高 低
Person obj = new Student(); //student将这个对象转换为Student类型,我们就可以使用Student类型的方法了!
//Student student = (Student) obj;
//student.go();
((Student) obj).go(); //子类转换成父类会丢失一些独有的方法!
Student student = new Student();
student.go();
Person person = student; }
}
多态小结:
1、前提:父类引用指向子类对象
2、把子类转换为父类,向上转型:会丢失一些独有的方法
3、把父类转换为子类,向下转型:强制转换
好处:
方便方法的调用,减少重复的代码,可以有效的提升利用率!是代码变的简洁
抽象:编程思想:三大特性,封装、继承、多态! 后面有抽象类!接口!
最新文章
- [BZOJ2391]Cirno的忧郁
- P4行为模型BMV2依赖关系安装:thrift nanomsg nnpy安装
- C++的黑科技
- 奥威Power-BI V11——凤凰涅槃,重磅来袭
- [Linux Tips] 1. 查看端口
- ASP.NET MVC 3和Razor中的@helper 语法
- 怎么修改mysql密码
- 输出图片的php代码前面不能有空白行
- UML学习-时序图
- FastDFS源代码分析之tracker协议分析
- JQuery的 jQuery.fn.extend() 和jQuery.extend();
- macOS Sierra安装Apache2.4+PHP7.0+MySQL5.7.16
- with原理__enter__、__exit__
- 根据xlsx模板生成excel数据文件发送邮件代码
- 背景图片的移动----background-attach-----background-repeat
- android 实践项目 总结 (修改)
- [JVM] - 一份<;自己动手写Java虚拟机>;的测试版
- pycharm tornado 项目 配置
- Office 2013 Excel 打开文档很慢很慢的解决方法
- ospf动态路由配置(单区域)