当前位置:网站首页>多态的理解以及作用
多态的理解以及作用
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类,可以提高可扩充性和可维护性。
边栏推荐
猜你喜欢

Thread application instance

程序猿入门攻略(十二)——数据的存储

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

Tutoriel (5.0) 10. Dépannage * fortiedr * fortinet Network Security expert NSE 5

Obligatoire pour les débutants, cliquez sur deux boutons pour passer à un contenu différent

codeforces每日5题(均1700)-第四天

IEDA refactor的用法

Imitation Jingdong magnifying glass effect (pink teacher version)

Advanced performance test series "24. Execute SQL script through JDBC"

数据降维——主成分分析
随机推荐
When converting from list to map, if a certain attribute may cause key duplication and exceptions, you can set the way to deal with this duplication
C文件输入操作
Excel finds the same value in a column, deletes the row or replaces it with a blank value
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
Reduce -- traverse element calculation. The specific calculation formula needs to be passed in and combined with BigDecimal
预处理和预处理宏
juypter notebook 修改默认打开文件夹以及默认浏览器
注解开发方式下AutowiredAnnotationBeanPostProcessor的注册时机
守望先锋世界观架构 ——(一款好的游戏是怎么来的)
How to print mybats log plug-in using XML file
《重构:改善既有代码的设计》读书笔记(下)
451-memcpy、memmove、memset的实现
Tutorial (5.0) 10 Troubleshooting * fortiedr * Fortinet network security expert NSE 5
2022 compilation principle final examination recall Edition
高级性能测试系列《24. 通过jdbc执行sql脚本》
Why should we build an enterprise fixed asset management system and how can enterprises strengthen fixed asset management
潇洒郎:彻底解决Markdown图片问题——无需上传图片——无需网络——转发给他人图片无缺失
yolov3 训练自己的数据集之生成train.txt
Processing strategy of message queue message loss and repeated message sending
Notes de lecture sur le code propre