封装和抽象概念之间的区别 [英] difference between encapsulation and abstraction concepts

查看:73
本文介绍了封装和抽象概念之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
抽象VS信息隐藏VS封装

Possible Duplicate:
Abstraction VS Information Hiding VS Encapsulation

有人可以向我解释面向对象程序设计中封装和抽象原理之间的主要区别(如果可能的话,还可以提供示例).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆