ByteBrawl - Private - Access Modifiers - Encapsulation

Access Modifiers - Private

The private access modifier restricts access to only from the same class only. It is the most restrictive access level and is commonly used for encapsulation.

PrivateExample.java

Main.java

As you can see, trying to access the private variable and method from the Main class results in a compilation error. However, we can access them through a public method within the same class:

This works because publicMethod() is a public method that can be accessed from outside the class, and it internally accesses the private members. This is a common pattern, frequently referred to as a "getter/setter" pattern, where you have 2 public methods that get or set a private variable respectively. This allows strictly controlled access to data and is very useful in many situations.