0
0
Javaprogramming~15 mins

Private access modifier in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept Flow - Private access modifier
Class with private member
Access private member inside class?
NoError if accessed outside
Yes
Access allowed, use member
End
The private modifier restricts access to class members only within the class itself.
code_blocksExecution Sample
Java
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());
  }
}
This code shows a private variable accessed inside the class via a public method.
data_tableExecution Table
StepActionEvaluationResult
1Create Box object bBox object with size=5b.size is private, stored as 5
2Call b.getSize()Inside getSize(), access private sizeReturns 5
3Print returned valueOutput value5
4Try to access b.size directly (not shown in code)Compile errorCannot access private field
5End--
💡 Execution stops after printing 5; direct access to private field is not allowed.
search_insightsVariable Tracker
VariableStartAfter Step 1After Step 2Final
b.sizeundefined555
keyKey Moments - 2 Insights
Why can't we access b.size directly outside the class?
How does the getSize() method access the private variable?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what value does getSize() return at step 2?
A0
B5
CCompile error
Dnull
photo_cameraConcept Snapshot
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
contractFull Transcript
This example shows how the private access modifier works in Java. A class Box has a private variable size set to 5. Inside the class, a method getSize() returns this private variable. When we create an object b of Box and call b.getSize(), it returns 5. However, trying to access b.size directly outside the class causes a compile error because size is private. This protects the variable from outside access. To get the value, we use a public method inside the class. This is how private access modifier helps keep data safe and controlled.