封装和抽象之间的确切区别是什么?


当前回答

封装把一些东西放在一个盒子里,给你一个窥视孔;这使你从混乱与齿轮。

抽象完全忽略了无关紧要的细节,比如物体是否有齿轮、棘轮、飞轮或核心;他们只是“走了”

封装的例子:

内裤 工具箱 钱包 手提包 胶囊 冷冻carbonite 一个盒子,上面有或没有按钮 一个墨西哥卷饼(严格来说,是卷饼周围的玉米粉圆饼)

抽象的例子:

“一组事物”是一种抽象(我们称之为聚合) “包含其他事物的事物”是一种抽象(我们称之为组合) “容器”是另一种“物装物”的抽象;注意,所有的封装示例都是不同种类的容器,但并不是所有的容器都展示/提供封装。例如,篮子是一种不封装其内容的容器。

其他回答

抽象或封装并不严格要求信息隐藏。信息可能会被忽略,但不一定要隐藏。

封装是一种将事物视为单一事物的能力,即使它可能由许多复杂的部分或思想组成。例如,我可以说我坐在一把“椅子”上,而不是指这把椅子上的许多不同部分,每个部分都有特定的设计和功能,它们精确地组合在一起,目的是让我的屁股舒适地离地板几英尺远。

Abstraction is enabled by encapsulation. Because we encapsulate objects, we can think about them as things which relate to each other in some way rather than getting bogged down in the subtle details of internal object structure. Abstraction is the ability to consider the bigger picture, removed from concern over little details. The root of the word is abstract as in the summary that appears at the top of a scholarly paper, not abstract as in a class which can only be instantiated as a derived subclass.

I can honestly say that when I plop my butt down in my chair, I never think about how the structure of that chair will catch and hold my weight. It's a decent enough chair that I don't have to worry about those details. So I can turn my attention toward my computer. And again, I don't think about the component parts of my computer. I'm just looking at a part of a webpage that represents a text area that I can type in, and I'm communicating in words, barely even thinking about how my fingers always find the right letters so quickly on the keyboard, and how the connection is ultimately made between tapping these keys and posting to this forum. This is the great power of abstraction. Because the lower levels of the system can be trusted to work with consistency and precision, we have attention to spare for greater work.

抽象和封装的区别。

许多答案和例子都具有误导性。

封装是将“数据”和“对该数据进行操作的函数”打包到单个组件中,并限制对某些对象组件的访问。 封装意味着对象的内部表示通常隐藏在对象定义之外的视图中。

抽象是一种表示基本特性而不包括实现细节的机制。

封装:——信息隐藏。 抽象:——实现隐藏。

示例(c++):

class foo{
    private:
        int a, b;
    public:
        foo(int x=0, int y=0): a(x), b(y) {}

        int add(){    
            return a+b;   
        } 
}  

foo类的任何对象的内部表示都隐藏在该类的外部。——>封装。 foo对象的任何可访问成员(data/function)都是受限的,只能由该对象访问。

foo foo_obj(3, 4);
int sum = foo_obj.add();

方法add的实现是隐藏的。——>抽象。

通过使用单个通用示例进行抽象和封装

------------------------------------------------------------------------------------------------------------------------------------

我们都用计算器来计算复杂的问题!

封装隐藏了实现细节,这些细节可能是通用的,也可能不是专门的行为。

抽象提供了一种泛化(例如,在一组行为之上)。

这里有一个很好的阅读:抽象、封装和信息隐藏,作者是Object Agency的Edward V. Berard。