当前位置:网站首页>多态的理解以及作用
多态的理解以及作用
2022-07-02 18:23:00 【夏诗曼CharmaineXia】
一、多态是什么
多态在面向对象中的定义:指为不同数据类型的实体提供统一的接口。
比如有动物(Animal)之类别(Class),而且由动物继承出类别鸡(Chicken)和类别狗(Dog),并对同一源自类别动物(父类)之一消息有不同的响应,如类别动物有“叫()”之动作,而类别鸡会“啼叫()”,类别狗则会“吠叫()”,则称之为多态。
二、多态的类型
多态分为静态多态和动态多态。
- 静态多态:在编译期间实现多态,相同的方法传递不同的参数,实现不同的效果。
C++代码实现:
// print()函数
void print(const char* str,int width);
void print(double i ,int width);
void print(const char* str);
// 使用print()函数时,编译器将根据所采取的用法使用有相应特征标的原型
print("abc",12);
print(2.2,55);
print("def");
- 动态多态:在运行期间实现多态,一个类的引用可以被赋值为不同的子类对象。
实现动态多态的必要条件:
- 编程语言要支持继承
- 子类可以重写(override)父类中的方法
- 父类引用可以指向子类对象
C#代码实现:
public class AnimalFactory{
public static Animal createAnimal(string type){
Animal animla=null;
switch(type){
case "cat":
animal=new Cat();
break;
case "bird":
animal=new Bird();
break;
case "dog":
animal=new Dog();
break;
}
}
}
三、多态解决什么问题
- 应用程序不必为每一个子类编写功能调用,只需要对父类进行处理即可。大大提高程序的可复用性。
- 子类的功能可以被父类的方法或引用变量所调用,就像Animal类,可以提高可扩充性和可维护性。
边栏推荐
- PHP-Parser羽毛球预约小程序开发require线上系统
- QT中的QPropertyAnimation使用和toast案列
- Processing strategy of message queue message loss and repeated message sending
- 潇洒郎:彻底解决Markdown图片问题——无需上传图片——无需网络——转发给他人图片无缺失
- 二进制操作
- Progress progress bar
- Usage of ieda refactor
- Page title component
- Yunna | why use the fixed asset management system and how to enable it
- PHP非对称加密方法私钥及公钥加密解密的方法
猜你喜欢
ICDE 2023|TKDE Poster Session(CFP)
论文导读 | 机器学习在数据库基数估计中的应用
Watchful pioneer world outlook Architecture - (how does a good game come from)
为什么要做企业固定资产管理系统,企业如何加强固定资产管理
Data dimensionality reduction principal component analysis
End to end object detection with transformers (Detr) paper reading and understanding
Thread application instance
全志A33使用主线U-Boot
Develop fixed asset management system, what voice is used to develop fixed asset management system
高级性能测试系列《24. 通过jdbc执行sql脚本》
随机推荐
横向越权与纵向越权[通俗易懂]
Gstore weekly gstore source code analysis (4): black and white list configuration analysis of security mechanism
C的内存管理
使用 Cheat Engine 修改 Kingdom Rush 中的金钱、生命、星
论文导读 | 关于将预训练语言模型作为知识库的分析与批评
教程篇(5.0) 09. RESTful API * FortiEDR * Fortinet 网络安全专家 NSE 5
[test development] software testing - concept
机器学习笔记 - 时间序列预测研究:法国香槟的月销量
Horizontal ultra vires and vertical ultra vires [easy to understand]
Data dimensionality reduction principal component analysis
Yolov3 trains its own data set to generate train txt
High frequency interview questions
A4988驱动步进电机「建议收藏」
Obligatoire pour les débutants, cliquez sur deux boutons pour passer à un contenu différent
Reduce -- traverse element calculation. The specific calculation formula needs to be passed in and combined with BigDecimal
[论文阅读] CA-Net: Leveraging Contextual Features for Lung Cancer Prediction
《代码整洁之道》读书笔记
PHP非对称加密方法私钥及公钥加密解密的方法
Novice must see, click two buttons to switch to different content
高级性能测试系列《24. 通过jdbc执行sql脚本》