Java constructors and encapsulation
Initialize private fields and validate changes through methods.
On this page
Classes and methods.
- Initialize private fields and validate changes through methods.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
A constructor initializes a new instance. Private fields keep normal external code from modifying state directly; methods define allowed operations.
This Counter rejects negative starting values and exposes a getter. Two instances have separate fields even though they share the same class definition.
Code example
class Counter {
private int value;
Counter(int start) {
if (start < 0) throw new IllegalArgumentException("negative start");
value = start;
}
void increment() { value++; }
int getValue() { return value; }
}
class Main {
public static void main(String[] args) {
Counter first = new Counter(2);
Counter second = new Counter(10);
first.increment();
System.out.println(first.getValue());
System.out.println(second.getValue());
}
}3 10
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
class Counter { private int value; Counter(int start) { if (start < 0) throw new IllegalArgumentException("negative start"); value = start; } void increment() { value++; } int getValue() { return value; }}class Main { public static void main(String[] args) { Counter first = new Counter(2); Counter second = new Counter(10); first.increment(); System.out.println(first.getValue()); System.out.println(second.getValue()); }}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Construct the first object. | first.value = 2 | — | |
| Construct independent state. | second.value = 10 | — | |
| Change only first. | first.value = 3, second.value = 10 | — | |
| Read the first value. | first.value = 3, second.value = 10 | 3 | |
| Read the unchanged second value. | first.value = 3, second.value = 10 | 3 10 |
Behind the scenes
How Java processes this code
The Java compiler produces bytecode. The JVM loads the class and invokes its main method.
Cost and common mistakes
O(1) operations and O(1) state per instance.
- A static field would be shared across instances.
- This minimal counter does not guard integer overflow after many increments.
Try it yourself
Call second.increment() twice.
Reveal answer and reasoning
The output becomes 3 and 12.