网站首页 > java教程 正文
本质上多态分两种:
1.编译时多态
(compile-time polymorphism) /(static polymorphism )
重载(overload)
public class TextFileStaticPolymorphism {
public String read() {
return "StaticPolymorphism".toString();
}
public String read(int limit) {
return "StaticPolymorphism".substring(0, limit);
}
public String read(int start, int stop) {
return "StaticPolymorphism".substring(start, stop);
}
}
2.运行时多态
(runtime polymorphism)/(dynamic polymorphism)
我们通常所说的多态指的都是运行时多态,也就是编译时不确定究竟调用哪个具体方法,一直延迟到运行时才能确定。
Java实现多态有 3 个必要条件:继承,重写,向上转型。只有满足这 3 个条件,开发人员才能够在同一个继承结构中使用统一的逻辑实现代码处理不同的对象,从而执行不同的行为。
public class GenericFile {
public String getFileInfo() {
return "Generic File Impl";
}
public class ImageFile extends GenericFile {
public String getFileInfo() {
return "Image File Impl";
}
}
GenericFile genericFile = new GenericFile();
String message = genericFile.getFileInfo();
System.out.println(message);
GenericFile genericFile2 = new ImageFile();
message = genericFile2.getFileInfo();
System.out.println(message);
结果
Generic File Impl
Image File Impl
3. 其他多态特性(Other Polymorphic Characteristics)
1. 强制转换(Coercion)
String str = “string” + 2;
2. 操作符重载( Operator Overloading)
String str = "2" + 2; // 22
int sum = 2 + 2; //4
3. 多态参数(Polymorphic Parameters)
use this keyword to point to global variables within a local context.
public class TextFile extends GenericFile {
private String content;
public String setContentDelimiter() {
int content = 100;
this.content = this.content + content;
}
}
4.多态子类型(Polymorphic Subtypes)
Polymorphic subtype conveniently makes it possible for us to assign multiple subtypes to a type and expect all invocations on the type to trigger the available definitions in the subtype.
多态子类型使我们可以方便地将多个子类型分配给一个类型,并期望对该类型的所有调用都能触发子类型中的可用定义。
GenericFile[] files = {
new ImageFile(),
new TextFile() };
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getFileInfo());
}
Image File Impl
Text File Impl
猜你喜欢
- 2024-09-27 Java多态重载和重写(类方法设计中多态与重载的区别是什么)
- 2024-09-27 什么是多态?Java为什么要用多态?(java中什么是多态性)
- 2024-09-27 别找了!月薪30k的T6大佬整理的Java多态知识点总结,限时收藏
- 2024-09-27 三十一、Java面向对象编程特性-多态
- 2024-09-27 Java多中包括态理解、多态实现、重写、转型和抽象类
- 2024-09-27 Java中的封装、继承和多态,你真的都懂了吗
- 2024-09-27 java基础之多态与向上转型,很用心的一篇笔记
- 2024-09-27 Java多态的介绍-学习日志(java的多态是什么)
- 2024-09-27 Java路径-25-Java多态(java路径错误)
- 2024-09-27 Java中的多态(基础语法)(java多态的定义和应用)
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- java反编译工具 (77)
- java反射 (57)
- java接口 (61)
- java随机数 (63)
- java7下载 (59)
- java数据结构 (61)
- java 三目运算符 (65)
- java对象转map (63)
- Java继承 (69)
- java字符串替换 (60)
- 快速排序java (59)
- java并发编程 (58)
- java api文档 (60)
- centos安装java (57)
- java调用webservice接口 (61)
- java深拷贝 (61)
- 工厂模式java (59)
- java代理模式 (59)
- java.lang (57)
- java连接mysql数据库 (67)
- java重载 (68)
- java 循环语句 (66)
- java反序列化 (58)
- java时间函数 (60)
- java是值传递还是引用传递 (62)
本文暂时没有评论,来添加一个吧(●'◡'●)