封装和抽象之间的确切区别是什么?
当前回答
封装把一些东西放在一个盒子里,给你一个窥视孔;这使你从混乱与齿轮。
抽象完全忽略了无关紧要的细节,比如物体是否有齿轮、棘轮、飞轮或核心;他们只是“走了”
封装的例子:
内裤 工具箱 钱包 手提包 胶囊 冷冻carbonite 一个盒子,上面有或没有按钮 一个墨西哥卷饼(严格来说,是卷饼周围的玉米粉圆饼)
抽象的例子:
“一组事物”是一种抽象(我们称之为聚合) “包含其他事物的事物”是一种抽象(我们称之为组合) “容器”是另一种“物装物”的抽象;注意,所有的封装示例都是不同种类的容器,但并不是所有的容器都展示/提供封装。例如,篮子是一种不封装其内容的容器。
其他回答
class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
// Aeroplane is a flying object
// Aeroplane can be fueled
// Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of
// flying object they are.
// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();
// ** Fueling code does not need know what kind of vehicle it is, so far
// as it can Fill Fuel**
我认为封装是实现抽象的一种方式。看看下面的链接。
抽象和封装
抽象是广义的术语。即封装是抽象的子集。
Abstraction | Encapsulation |
---|---|
It solves an issue at the design level. | Encapsulation solves an issue at implementation level. |
hides the unnecessary detail but shows the essential information. | It hides the code and data into a single entity or unit so that the data can be protected from the outside world. |
Focuses on the external lookout. | Focuses on internal working. |
Lets focus on what an object does instead of how it does it. | Lets focus on how an object does something. |
Example: Outer look of mobile, like it has a display screen and buttons. | Example: Inner details of mobile, how button and display screen connect with each other using circuits. |
示例:解决方案架构师是创建整个解决方案的高级抽象技术设计的人,然后将该设计移交给开发团队进行实现。 在这里,解决方案架构师充当抽象,而开发团队充当封装。
举例:用户数据的封装(组网)
图片由
Abstraction (or modularity) – Types enable programmers to think at a higher level than the bit or byte, not bothering with low-level implementation. For example, programmers can begin to think of a string as a set of character values instead of as a mere array of bytes. Higher still, types enable programmers to think about and express interfaces between two of any-sized subsystems. This enables more levels of localization so that the definitions required for interoperability of the subsystems remain consistent when those two subsystems communicate. Source
Java示例
抽象和封装的区别。
封装意味着隐藏数据,比如使用getter和setter等。
抽象意味着-隐藏实现使用抽象类和接口等。