封装和抽象之间的确切区别是什么?
当前回答
一种防止特定对象的数据被外部函数故意或意外误用的机制叫做“数据封装”。
在不包括背景细节或解释的情况下表现基本特征的行为被称为抽象
其他回答
我试图在抽象和封装之间画一条线,根据我的观点,抽象更多的是概念性的东西,而封装是抽象实现的一种。因为一个人可以隐藏数据而不封装,例如使用私有常数或变量;所以我们可以用数据隐藏进行封装,但数据隐藏并不总是封装。在下面这段代码中,我试图描述这些概念的最简单形式。
// Abstraction
interface IOperation
{
int SquareNumber();
}
public class Operation
{
// Data hiding
private int number;
public Operation(int _number)
{
this.number = _number;
}
// Encapsulation
public int SquareNumber()
{
return number * number;
}
}
在行动,
IOperation obj = new Operation(2);
// obj.number <--- can't access because hidden from world using private access modifier but not encapsulated.
obj.SquareNumber(); // cannot access internal logic to calculate square because logic is hidden using encapsulation.
一种防止特定对象的数据被外部函数故意或意外误用的机制叫做“数据封装”。
在不包括背景细节或解释的情况下表现基本特征的行为被称为抽象
封装意味着隐藏数据,比如使用getter和setter等。
抽象意味着-隐藏实现使用抽象类和接口等。
上面提供了很多很好的答案,但我将在这里介绍我的(Java)观点。
数据封装简单地说就是包装和控制类中逻辑分组数据的访问。它通常与另一个关键字-数据隐藏相关联。这是在Java中使用访问修饰符实现的。
一个简单的例子是定义一个私有变量,并使用getter和setter方法访问它,或者将一个方法设置为私有,因为它只在类中使用。用户不需要知道这些方法和变量。
注意:不要误解封装只是关于数据隐藏。当我们说封装时,重点应该是将相关数据和行为分组、打包或捆绑在一起。
另一方面,数据抽象是泛化的概念,这样底层的复杂逻辑就不会暴露给用户。在Java中,这是通过使用接口和抽象类实现的。
的例子,
Lets say we have an interface Animal and it has a function makeSound(). There are two concrete classes Dog and Cat that implement this interface. These concrete classes have separate implementations of makeSound() function. Now lets say we have a animal(We get this from some external module). All user knows is that the object that it is receiving is some Animal and it is the users responsibility to print the animal sound. One brute force way is to check the object received to identify it's type, then typecast it to that Animal type and then call makeSound() on it. But a neater way is to abstracts thing out. Use Animal as a polymorphic reference and call makeSound() on it. At runtime depending on what the real Object type is proper function will be invoked.
详情请点击这里。
复杂的逻辑是在电路板中,封装在一个触摸板中,并提供了一个漂亮的界面(按钮)来将其抽象给用户。
附注:以上链接是我的个人博客。
让我们以堆栈为例。它可以使用数组或链表来实现。但它支持的操作是推送和弹出。
Now abstraction is exposing only the interfaces push and pop. The underlying representation is hidden (is it an array or a linked list?) and a well-defined interface is provided. Now how do you ensure that no accidental access is made to the abstracted data? That is where encapsulation comes in. For example, classes in C++ use the access specifiers which ensure that accidental access and modification is prevented. And also, by making the above-mentioned interfaces as public, it ensures that the only way to manipulate the stack is through the well-defined interface. In the process, it has coupled the data and the code that can manipulate it (let's not get the friend functions involved here). That is, the code and data are bonded together or tied or encapsulated.