问题描述
我似乎不太了解两个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.
这篇关于抽象和多态有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!