wan*_*UDY 6 oop encapsulation abstraction
可能重复:
抽象VS信息隐藏VS封装
有人可以向我解释面向对象编程中封装和抽象原则之间的主要区别(如果可能的话,还有示例).
样品:
// NO ABSTRACTION, NO ENCAPSULATION
const int catLegs = 4;
const int spiderLegs = 8;
Leg[] catLegs;
Leg[] spiderLegs;
void MakeCatRun(Distance b) { for (int i=0; i<catLegs; ++i) catLegs[i] += b; }
void MakeSpiderRun(Distance b) { for (int i=0; i<spiderLegs; ++i) spiderLegs[i] += b; }
Run Code Online (Sandbox Code Playgroud)
封装:
// ENCAPSULATION
class Cat
{
Leg[] legs;
int nLegs;
public void Run(Distance b) { for (int i=0; i < nLegs; ++i) leg[i] += b; }
}
class Spider
{
Leg[] legs;
int nLegs;
public void Run(Distance b) { for (int i=0; i < nLegs; ++i) leg[i] += b; }
}
Run Code Online (Sandbox Code Playgroud)
抽象:
// ABSTRACTION
class LivingBeing
{
Leg[] legs;
int nLegs;
public void Run(Distance b) { for (int i=0; i < nLegs; ++i) leg[i] += b; }
}
class Cat: LivingBeing { }
class Spider: LivingBeing { }
Run Code Online (Sandbox Code Playgroud)
抽象是质量,我们只是不打扰不必要的内部机制(实现),并可以处理系统/对象,查看基本要素.
例如:在汽车上施加制动时,您根本不在乎是否有空气制动或液压制动.抽象在这里以踏板推动的形式出现.
封装是通过在容器内打包(封装)实现细节(在上述情况下隐藏破坏机制和微小组件与视力或物理接触)使上述(抽象)成为可能的事情.
所以,Encapsulation实际上提供了抽象!
如果环顾四周,你可以在现实世界的任何地方看到它.编程中也有它 - 如果有人为你提供了一个排序整数列表的类,你真的不需要打扰它使用的排序算法(冒泡排序/快速排序),抽象使你有可能通过方法的整数列表; 这就对了.
class Sorter
{
public List<Integer> Sort(List<Integer>)//Only this method is seen outside
{
String pattrenName=this.AdvancedPatternFinder();
this.Advancedsorter(pattenName);
//Return sorted list
}
private String AdvancedPatternFinder(){}//NOT seen from outside
private void Advancedsorter(String pattrenName){}//NOT seen from outside
}
Run Code Online (Sandbox Code Playgroud)
请参阅下面的动画,了解如何通过封装内部细节来提供整洁的抽象!
图片提供:这个博客
| 归档时间: |
|
| 查看次数: |
4771 次 |
| 最近记录: |