您的位置:首页 > 其它

面向对象:多态 Polymorphism、重载、重写、继承

2017-10-07 16:31 246 查看

1. 声明

本文来源于维基百科:

Polymorphism (computer science)

2.定义

In programming languages and type theory, polymorphism or polyphormism is the provision of a single interface to entities of different types.

对不同类型实体的单一接口

3.分类

注:分类方法之一

3.1 Ad hoc polymorphism

when a function denotes different and potentially heterogeneous implementations depending on a limited range of individually specified types and combinations. Ad hoc polymorphism is supported in many languages using function overloadin

代码示例:

program Adhoc;

function Add(x, y : Integer) : Integer;
begin
Add := x + y
end;

function Add(s, t : String) : String;
begin
Add := Concat(s, t)
end;

begin
Writeln(Add(1, 2));                   (* Prints "3"             *)
Writeln(Add('Hello, ', 'World!'));    (* Prints "Hello, World!" *)
end.


Ad-hoc polymorphism 又称重载 Overloading( function overloading or operator overloading)

3.2 Parametric polymorphism

when code is written without mention of any specific type and thus can be used transparently with any number of new types. In the object-oriented programming community, this is often known as generics or generic programming. In the functional programming community, this is often shortened to polymorphism.

代码示例:

class List<T> {
class Node<T> {
T elem;
Node<T> next;
}
Node<T> head;
int length() { ... }
}

List<B> map(Func<A, B> f, List<A> xs) {
...
}


Parametric polymorphism

1. 在C++中体现为 templates 模板

2. 在Java中体现为 generics 泛型

3.3 Subtyping

(also called subtype polymorphism or inclusion polymorphism): when a name denotes instances of many different classes related by some common superclass. In the object-oriented programming community, this is often referred to as simply Inheritance.

代码示例:

abstract class Animal {
abstract String talk();
}

class Cat extends Animal {
String talk() {
return "Meow!";
}
}

class Dog extends Animal {
String talk() {
return "Woof!";
}
}

static void letsHear(final Animal a) {
println(a.talk());
}

static void main(String[] args) {
letsHear(new Cat());
letsHear(new Dog());
}


Subtype polymorphism 体现为 继承 Inheritance 后的 重写 Overriding
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: