当前位置:网站首页>多态的理解以及作用
多态的理解以及作用
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类,可以提高可扩充性和可维护性。
边栏推荐
- Golang并发编程——goroutine、channel、sync
- IDEA编辑器去掉sql语句背景颜色SQL语句警告No data sources are configured to run this SQL...和SQL Dialect is Not Config
- C file input operation
- [0701] [论文阅读] Alleviating Data Imbalance Issue with Perturbed Input During Inference
- 【测试开发】软件测试—概念篇
- MySQL
- End to end object detection with transformers (Detr) paper reading and understanding
- Date tool class (updated from time to time)
- Windows2008R2 安装 PHP7.4.30 必须 LocalSystem 启动应用程序池 不然500错误 FastCGI 进程意外退出
- Data dimensionality reduction factor analysis
猜你喜欢

高级性能测试系列《24. 通过jdbc执行sql脚本》

注解开发方式下AutowiredAnnotationBeanPostProcessor的注册时机

Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3

Transformation of thinking consciousness is the key to the success or failure of digital transformation of construction enterprises

机器学习笔记 - 时间序列预测研究:法国香槟的月销量

Yolov3 trains its own data set to generate train txt

论文导读 | 机器学习在数据库基数估计中的应用

性能测试如何创造业务价值

Tutorial (5.0) 10 Troubleshooting * fortiedr * Fortinet network security expert NSE 5

Markdown基础语法
随机推荐
横向越权与纵向越权[通俗易懂]
Golang:[]byte to string
Excel finds the same value in a column, deletes the row or replaces it with a blank value
教程篇(5.0) 09. RESTful API * FortiEDR * Fortinet 网络安全专家 NSE 5
《代碼整潔之道》讀書筆記
450-深信服面经1
潇洒郎:彻底解决Markdown图片问题——无需上传图片——无需网络——转发给他人图片无缺失
教程篇(5.0) 10. 故障排除 * FortiEDR * Fortinet 网络安全专家 NSE 5
高级性能测试系列《24. 通过jdbc执行sql脚本》
mybatiesHelperPro工具必须的可以生成到对应项目文件夹下
The mybatieshelperpro tool can be generated to the corresponding project folder if necessary
PyTorch函数中的__call__和forward函数
Microservice technology - distributed global ID in high concurrency
Memory management of C
Talk about the design of red envelope activities in e-commerce system
Data dimensionality reduction factor analysis
Introduction to the paper | application of machine learning in database cardinality estimation
全志A33使用主线U-Boot
【测试开发】一文带你了解什么是软件测试
冒泡排序数组