Concept Flow - Private access modifier
Class with private member
Access private member inside class?
No→Error if accessed outside
Yes
Access allowed, use member
End
The private modifier restricts access to class members only within the class itself.
class Box { private int size = 5; int getSize() { return size; } } public class Main { public static void main(String[] args) { Box b = new Box(); System.out.println(b.getSize()); } }
| Step | Action | Evaluation | Result |
|---|---|---|---|
| 1 | Create Box object b | Box object with size=5 | b.size is private, stored as 5 |
| 2 | Call b.getSize() | Inside getSize(), access private size | Returns 5 |
| 3 | Print returned value | Output value | 5 |
| 4 | Try to access b.size directly (not shown in code) | Compile error | Cannot access private field |
| 5 | End | - | - |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| b.size | undefined | 5 | 5 | 5 |
private modifier: - Used to restrict access to class members - Members are accessible only inside their own class - Outside access causes compile errors - Use public methods to access private members - Helps protect data and enforce encapsulation