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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值