Can an object access a private member of a class in Java

  • Inside the class, access to a private variable is open without restrictions;
  • The nested class has full access to all (including private) members of the containing class;
  • Access to private variables from the outside can be organized through methods other than private methods provided by the class developer. For example: getX() and setX().
  • Through the Reflection API:

class Example {
    private int number = 54;
}
// ...
Example example = new Example();
Field field = Example.class.getDeclaredField("number");
field.setAccessible(true);
int fieldValue = (int) field.get(example);
// ...


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed