» 多态性(编程)

多态性(编程)

1967
  • Christopher Strachey
Computer programming workspace demonstrating polymorphism with code snippets.

Polymorphism, from Greek for “many shapes,” allows objects of different classes to be treated as objects of a common superclass. It enables a single interface, such as a method name, to be used for a general class of actions. The specific action is determined by the exact type of the object at runtime. This is often achieved through method overriding.

Polymorphism is a powerful concept that allows for writing flexible and decoupled code. The most common form in OOP is subtype polymorphism, which is enabled by inheritance and 方法 overriding. When a subclass provides a specific implementation for a method that is already defined in its superclass, it is called overriding. A variable of the superclass type can refer to an object of any of its subclasses. When a method is called on this variable, the version of the method that gets executed is the one belonging to the object’s actual class, not the variable’s type. This decision is made at runtime, a process known as dynamic dispatch or late binding.

For example, consider a superclass ‘Shape’ with a method ‘calculateArea()’. Subclasses like ‘Circle’ and ‘Rectangle’ can inherit from ‘Shape’ and provide their own specific implementations of ‘calculateArea()’. A program can then have a list of ‘Shape’ objects, containing both ‘Circle’ and ‘Rectangle’ instances. When iterating through the list and calling ‘calculateArea()’ on each element, the correct formula will be used for each shape automatically. This eliminates the need for long ‘if-else’ or ‘switch’ statements to check the type of each object, leading to cleaner, more extensible code. New shapes can be added to the system without modifying the code that processes them.

UNESCO Nomenclature: 1203
- 计算机科学

类型

抽象系统

中断

递增

使用方法

广泛使用

前体

  • C 语言中的函数指针概念
  • 通用编程概念
  • 继承,提供子类型多态性所需的类层次结构
  • the need for flexible and extensible 软件 系统

应用

  • drawing different shapes (‘circle’, ‘square’) using a single ‘draw()’ method call
  • processing various document types (‘pdf’, ‘word’) with a generic ‘print()’ function
  • implementing user interface event handlers
  • 可以容纳不同但相关类型的对象的通用集合
  • 依赖注入框架

专利:

NA

潜在的创新想法

级别需要会员

您必须是!!等级!!会员才能访问此内容。

立即加入

已经是会员? 在此登录
Related to: polymorphism, overriding, dynamic dispatch, late binding, subtype, interface, abstraction, oop, method overriding, runtime.

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

迎接新挑战
机械工程师、项目、工艺工程师或研发经理
有效的产品开发

可在短时间内接受新的挑战。
通过 LinkedIn 联系我
塑料金属电子集成、成本设计、GMP、人体工程学、中高容量设备和耗材、精益制造、受监管行业、CE 和 FDA、CAD、Solidworks、精益西格玛黑带、医疗 ISO 13485

我们正在寻找新的赞助商

 

您的公司或机构从事技术、科学或研究吗?
> 给我们发送消息 <

接收所有新文章
免费,无垃圾邮件,电子邮件不分发也不转售

或者您可以免费获得完整会员资格以访问所有受限制的内容>这里<

历史背景

(如果日期不详或不相关,例如 "流体力学",则对其显著出现的时间作了四舍五入的估计)。

相关发明、创新和技术原理

滚动至顶部

你可能还喜欢