Core OOPS:封装

huangapple go评论68阅读模式
英文:

Core OOPS : Encapsulation

问题

昨天在一次面试中,有人问我:“封装在内部是如何工作的?”我真的很困惑,因为在我看来,封装只是简单地意味着“一个类的状态只能通过其公共接口访问”。但是当涉及内部工作原理时,我无法用词言表。所以如果有人能够解释一下,那将会非常有帮助。

英文:

Yesterday in an Interview I was asked
How Does Encapsulation works internally ?
I was really confused because as per me Encapsulation is simply
"The state of a class should only be accessed through its public interface."
but when it comes to internal working I ran out of words.So if anyone can explain that it would be so helpful.

答案1

得分: 2

我同意评论者的观点,要求澄清是个好主意——好的问题甚至可以比好的回答更加出色,这使你能够确保你实际上在回答他们所认为的问题。

在这种情况下,我假设他们想要你解释 Java 如何确保程序员不违反封装。这涉及到:

  • 内置的语法和语义,用于将字段/方法标记为 public、private、protected 或 package-protected。
  • 编译器检查以确保不违反这些规定。
  • (外部)工具可用于检测与封装有关的代码异味,例如从构造函数内部调用可重写方法。
  • (稍微离题一些)无法直接访问程序内存,这使得在 Java 中不可能像在 C/C++ 中那样进行重新解释转换(reinterpret-casts);这也保护了封装性。

你本可以通过这样询问来确保他们想要的是什么 “您是否在谈论 Java 如何确保程序员不违反封装,即不通过其公共接口之外的方式访问对象的状态?”

还有其他一些答案:

  • 使用有意义的注释,通过 JavaDoc 在 IDE 内部和可浏览的文档中轻松访问,这些注释使程序员能够理解类的预期用法和组合方式。
  • 强制执行封装的强编码约定,例如将字段设置为最严格的访问权限,并且只将那些实际上应该是公共的部分设置为 public。
英文:

I agree with commenters that asking for clarifications is a good idea - good questions can be even better than good answers, and allow you to ensure that you are actually answering what they think that they are asking.

In this case, I assume that they wanted you to explain how Java ensures that programmers do not violate encapsulation. This involves

  • built-in syntax and semantics for marking fields / methods as public, private, protected, or package-protected.
  • compiler checks to ensure that these are not violated
  • (external) tools available to detect code smells relating to encapsulation, such as calls to overridable methods from within a constructor.
  • (somewhat more far-fetched) no direct access to program memory, making, for example, reinterpret-casts such as found in C / C++ unavailable in Java; this also preserves encapsulation.

You could have ensured that this is what they wanted by asking "are you referring to how Java ensures that programmers do not violate encapsulation, that is, that they do not access the state of objects except through their public interface?"

Additional answers come to mind:

  • use of meaningful comments, easily accessible via JavaDoc both in-IDE and as browsable documentation, that allow programmers to understand how classes are meant to be used and composed.
  • strong coding conventions that enforce encapsulation, such as setting fields to the most restrictive access possible, and only making public those parts that should actually be public.

huangapple
  • 本文由 发表于 2020年10月7日 15:35:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64239382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定