封装/抽象 [英] Encapsulation / Abstraction

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

问题描述

可能的重复:
抽象和封装的区别?
抽象和封装有什么区别?

我注意到在讨论 OOP 设计时封装和抽象的概念很重要.但是,我不太确定它们彼此之间有何不同.我读过很多文章和帖子(其中大部分来自这个网站),它们只是相互矛盾.

I've noticed that the notion of Encapsulation and Abstraction are important when discussing OOP design. However, I'm not too sure on how they differ from one another. I've read a bunch of articles and posts (of which most of them are from this site) which merely contradict each other.

据我所知,抽象是一种分解现实世界对象复杂性的方法.这种分解可能涉及创建几个共同代表现实世界对象的对象.抽象也可以有很多层,类继承就是一个例子.

It's my understanding that Abstraction is a means of decomposing the complexity of real-world objects. This decomposition may involve the creation of several objects that collectively represent a real-world object. Abstraction can also have many layers to it, class inheritance is an example of when this would be the case.

封装是在类中隐藏内部实现数据的过程.访问修饰符和访问器方法等语言特性是其中的关键.

Encapsulation is the process of hiding away the inner implementation data within a class. Language features such as Access modifiers and Accessor methods are key in this.

如果这些定义是正确的(如果我错了,请纠正我),接口将用于什么原则?抽象?因为一组现实世界的对象可以总结在一个界面中?或者封装,接口本身可以用来暴露对象的特性而不暴露内部功能.

If these definitions are true (correct me if I'm wrong), under what principle would Interfaces be used for? Abstraction? because a group of real-world objects can be summarized in an interface? Or Encapsulation, where the Interface itself can be used to expose the features of an object without revealing the inner functionality.

如果可能,您能否还提供一个简短的示例,以便清楚地区分这两个原则?

If possible could you also provide an brief example, that will clearly distinguish these two principles?

干杯.

推荐答案

接口属于抽象类别.他们将一个类的共同特征抽象"或分解为另一个类,迫使所有子类遵守它们的约定并实现其所有方法.在我看来,我认为抽象和接口是代码重用,它促进了更易于维护的代码,而封装主要允许更大的安全措施.它们都是主要的 OOP 概念,并且确实有一些比较.

interfaces belong under the abstraction category. They 'abstract' or factor out the common features of a class into another class, forcing all sub-classes to abide by their contract and implement all of its methods. In my mind I think of abstraction and interfaces as code-reuse which facilitates more maintainable code, whereas encapsulation primarily allows for greater measures of security. They are both major OOP concepts and do share some comparisons.

这篇关于封装/抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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