封装和抽象概念的区别 [英] difference between encapsulation and abstraction concepts
本文介绍了封装和抽象概念的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
抽象 VS 信息隐藏 VS 封装
有人可以向我解释面向对象编程中封装和抽象原则之间的主要区别吗(如果可能的话).
Can somebody explain to me the main differences between the principles of encapsulation and abstraction in objected-oriented programming (if possible with examples).
推荐答案
示例:
// 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; }
封装:
// 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; }
}
抽象:
// 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 { }
这篇关于封装和抽象概念的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文