javaencapsulationinformation-hiding

How do compilers perform information hiding and encapsulation?


When I create a Java class definition, I can use private, public, protected and other keywords to control how the members and methods are accessed:

public class Bowel{
  private Movement privatePoop = new Movement(1);
  public Movement publicPoop = new Movement(2);

  ...
}

What does the compiler do differently when it's creating bytecode for the privatePoop and publicPoop method and member? If someone externally tries to access privatePoop, how does it know/signify to the JVM that they shouldn't be able to do it?


Solution

  • Basically the compiled classes and members are marked as public, private, etc. It is pure syntactical protection: the compiler won't compile an access to a private member from outside the enclosing class. All this you can bypass at runtime by reflection.