17 多态
动态编译:类型
即同一个方法可以根据发送对象的不同而采用多种不同的行为方式
一个对象的实际类型是确定的,但可以指向对象的引用的类型有很多(父类,有关系的类)
存在的条件
-
有继承关系
-
子类重写父类方法
-
父类引用指向子类对象
public class Person {
public void run(){
System.out.println("run");
}
}
public class S*tudent extends Person{
注意事项:
-
是方法的多态,属性没有多态
-
父类和类,有联系 类型转换异常 ClassCastException
-
存在条件: 继承关系 方法需要重写 父类引用指向子类子类对象
Father f1 = new Son();
-
static 方法 属于类, 它不属于实例
-
final 常量
-
private
-
instance of 关键字
引用类型,判断一个对象是什么类型。两个类之间是否存在父子关系
System.out.println(x instanceof y);
能不能编译通过,
看右边的实际类型和要比较的类型 x指向的实际类型是不是y的子类
//继承关系
//object > string
//object > person > teacher
//object > person > student
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);//编译报错
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);//编译报错
//Person p = new Person();
System.out.println(p instanceof Person); // true
System.out.println(p instanceof Student); // false
//类型之间的转换:父 子
//子类转换为父类 可能丢失自己的本来的方法
//高 低
Person obj = new Student();
//obj.go();
//obj 将这个对象转换为student类型,我们就可以使用Student类型的方法了
//Student student = (Student)obj;
//student.go();
((Student)obj).go();
//
Person p2 = new Person();
Student s2 = (Student) p2; // runtime error! ClassCastException!
//p2转型为Student会失败,因为p2的实际类型是Person,不能把父类变为子类
Student student = new Student();
Person person = student;
person.go();//报错
1.只能父类引用指向子类的对象
2.把子类转换为父类 向上转型,直接转,丢失子类中原本可直接调用的特有方法
3.把父类转换为子类 向下转型 强制转 会丢失父类被子类重写的方法 向下转型很可能会失败。失败的时候,Java虚拟机会报ClassCastException
。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)