Java constructors and encapsulation
A constructor initializes a new instance. Private fields keep normal external code from modifying state directly; methods define allowed operations.
Java
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());
}
}