本文介绍了抽象和多态性有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎不太了解两个OOP概念.您能解释一下什么是抽象多态,最好是带有真实示例和代码吗?

I seem to not understand two OOP concepts very well. Could you explain what abstraction and polymorphism are, preferably with real examples and code?

谢谢.

推荐答案

抽象

想象一个分数类:

Abstraction

Imagine a fraction class:

class fraction:
    int denominator
    int numerator

现在有两个对象:

fraction(obj1): denominator=-1 numerator=-1
fraction(obj2): denominator=1  numerator=1

两个对象的值均为1:(1/1) == (-1)/(-1).您不会期望它们的行为与外界有所不同.那是抽象的.您将对象保存的数据抽象为逻辑视图,甚至在幕后,还有其他事情.从理论上讲,您具有一个等价关系,并且具有不同的等价组:

Both objects have the value 1: (1/1) == (-1)/(-1). You wouldn't expect they behave any different to the outside. That's abstraction. You abstract the data your object holds into a logical view, even tho behind the scenes, there are other things. Theoretically, you have got a equivalence relation, with different equivalence groups:

[1]=(1, 1), (-1, -1), (5, 5), ...
[2]=(2, 4), (-2, -4), ...
...

有一个抽象函数可以将内部细节抽象到外部:

And there is a abstraction function that abstracts the internal details to the outside:

f((1, 1)) = [1]
f((-1, -1)) = [1]

它将从具体值映射到对象的抽象值.通过编写例如(-1,-1)到(1,1)的构造函数映射并为类编写equals函数,可以实现此目的.

It maps from concrete values to the abstract values of an object. You do that by writing for example a constructor mapping (-1, -1) to (1, 1) and by writing a equals function for your class.

想象一下一支笔和两个派生类:

Imagine a pen and two derived classes:

class pen:
    void draw(int x, int y)

class pen_thin extends pen:
    void draw(int x, int y) { color(x, y) = green; }

class pen_thick extends pen:
    void draw(int x, int y) { color(x, y) = green;
                              color(x, y+1) = green; }
and two objects:
    pen_thin(p1)
    pen_thick(p2)

两支笔都可以画画.您一般的笔"不能自己绘制.它只是pen_thin,pen_thick和许多其他笔的接口.您说:obj1.draw(1,0);作为用户,obj1是粗笔还是细笔都无关紧要,在编译时对于编译器也无关紧要.该调用的行为是多态的.这是动态多态性(在运行时发生),这就是人们通常的意思. 静态多态性发生在编译时:

Both pens can draw. your general "pen" cannot draw itself. It's just an interface to pen_thin, pen_thick and lots of other pens. You say: obj1.draw(1, 0); and whether obj1 is a thick or a thin pen doesn't matter to you as a user, neither to the compiler at compile time. The call behaves polymorphic. It's dynamic polymorphism (happens at runtime) and that's what people usually mean. Static Polymorphism happens at compile time:

class colorizer:
    void colorize(shirt s)
    void colorize(pants p)

这称为超载.您呼叫obj.colorize(something).如果您以衬衫参考来称呼它,它将以带衬衫的版本来称呼它.如果您以裤子参考来称呼它,它将称呼裤子版本.此处所做的选择是在编译时 .

That's called overloading. You call obj.colorize(something). If you call it with a shirt reference, it will call the version taking a shirt. And if you call it with a pant reference, it will call the pants version. The choice done here is at compile-time.

这篇关于抽象和多态性有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 10:50