Search code examples
javaoopencapsulationconcept

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.


Solution

  • 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.