封装和抽象之间的确切区别是什么?
当前回答
封装:对对象的实际用户隐藏不需要的/不期望的/适当的实现细节。 如。
List<string> list = new List<string>();
list.Sort(); /* Here, which sorting algorithm is used and hows its
implemented is not useful to the user who wants to perform sort, that's
why its hidden from the user of list. */
抽象:是一种提供泛化的方法,因此是处理大量不同对象的通用方法。如。
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**
其他回答
封装把一些东西放在一个盒子里,给你一个窥视孔;这使你从混乱与齿轮。
抽象完全忽略了无关紧要的细节,比如物体是否有齿轮、棘轮、飞轮或核心;他们只是“走了”
封装的例子:
内裤 工具箱 钱包 手提包 胶囊 冷冻carbonite 一个盒子,上面有或没有按钮 一个墨西哥卷饼(严格来说,是卷饼周围的玉米粉圆饼)
抽象的例子:
“一组事物”是一种抽象(我们称之为聚合) “包含其他事物的事物”是一种抽象(我们称之为组合) “容器”是另一种“物装物”的抽象;注意,所有的封装示例都是不同种类的容器,但并不是所有的容器都展示/提供封装。例如,篮子是一种不封装其内容的容器。
抽象和封装的区别。
简而言之
抽象使用->封装 & 封装使用->数据隐藏
OR
数据隐藏是封装和的子集 封装是抽象的一个子集
参考:http://www.tonymarston.co.uk/php-mysql/abstraction.txt
抽象和封装都是用来隐藏数据的。但是有很大的不同。
封装
封装是将数据和对数据进行操作的代码绑定或包装成一个称为Class的单元的过程。
封装在实现级别解决了问题。
在类中,可以使用私有或受保护的访问修饰符来隐藏数据。
抽象
抽象是隐藏无关细节的概念。换句话说,通过对用户隐藏不必要的细节,使复杂的系统变得简单。
抽象在设计层面解决了问题。
可以通过在Java中创建接口和抽象类来实现抽象。
在ruby中,你可以通过创建模块来实现抽象。
示例:我们使用(收集,映射,减少,排序…)方法的枚举模块与数组和ruby哈希。
抽象是对用户隐藏无用的数据 封装是将数据绑定到一个胶囊(类)中。 我认为封装是我们实现抽象的方式。