day 18 多态
## 多态
父类的引用指向子类
子类不能指向父类
把子类转换为父类,要向上转型
把父类转换为子类,要向下转型,强制转换,可能会丢失一些方法
多态方便方法的调用,减少重复的代码,提高利用率
子类:
1 ``` 2 3 public class Student extends Person { 4 5 public void go(){ 6 System.out.println("go"); 7 } 8 /* 9 多态的注意事项: 10 1. 多态是方法的多态,属性没有多态 11 2. 父类和子类才有联系:类型转换异常ClassCastException 12 3. 多态存在条件:继承关系,方法需要重写,父类的引用指向子类的对象 father f1 = new son(); 13 无法重写的方法: 14 1. static方法 15 2. final常量 16 3. private方法 17 */ 18 } 19 20 ```
父类:
1 ``` 2 public class Person { 3 4 5 } 6 ```
当父类对象转换为子类时,可以转换,无法调用子类的方法
需要强制转换才可以调用
将子类转换为父类可能会丢失自己的方法
1 ``` 2 public static void main(String[] args) { 3 4 //类型之间的转换:父类转换子类 可以转 5 Person student = new Student(); 6 //student.go(); student是Person类型不能调用Student方法 7 //将student转换为Student类型可以调用Student的方法 8 Student student1 = (Student) student; 9 student1.go(); 10 ((Student)student).go(); 11 12 13 // 子类转换为父类可能会丢失自己本身的一些方法 14 Student s1 = new Student(); 15 s1.go(); 16 Person person = s1; 17 //person.go(); 18 ```
多态的总结:
1. 多态时方法的多态,属性没有多态
2. 父类和子类之间才有联系,类型转换异常错误:ClassCastException
3. 多态存在的条件:继承关系,方法的重写,父类的引用指向子类的对象 father f1 = new son;
无法重写的方法:
static方法 final 常量 private方法
## instanceof
1 ``` 2 //System.out.println(x instanceof y); 3 //能否编译通过,取决于x y之间是否有父子关系。有为true 没有是false 4 Object o = new Student(); 5 //object > person> student 6 System.out.println(o instanceof Student);//true 7 System.out.println(o instanceof Person);//true 8 System.out.println(o instanceof Object);//true 9 System.out.println(o instanceof Teacher);//false 10 System.out.println(o instanceof String);//flase 11 12 13 Person person = new Student(); 14 System.out.println(person instanceof Student);//true 15 System.out.println(person instanceof Person);//true 16 System.out.println(person instanceof Object);//true 17 System.out.println(person instanceof Teacher);//false 18 //System.out.println(person instanceof String);//编译报错 19 20 21 Student student = new Student(); 22 23 System.out.println(student instanceof Student);//true 24 System.out.println(student instanceof Person);//true 25 System.out.println(student instanceof Object);//true 26 //System.out.println(student instanceof Teacher);//编译报错 27 //System.out.println(student instanceof String);//编译报错 28 ```
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗