Classes and objects
Combine state and behavior in a Java class and follow a constructor call.
Create two independent objects
A class declares fields and methods. Calling its constructor with new creates an instance and initializes its state. Two separate instances have separate copies of their instance fields.
How it works
Build two small objects of the same class with different starting values. Then run one method on only the first object and inspect both. The class supplies shared definitions, while each instance holds its own field values.
Keep changes behind a method
Give a counter a private field and an increment method. This lets the class control updates and gives callers an operation with a clear name. A public read method can expose the current value without exposing direct assignment.
Code example
public class Main {
static class Counter {
private int count;
Counter(int start) {
count = start;
}
void increment() {
count++;
}
int value() {
return count;
}
}
public static void main(String[] args) {
Counter first = new Counter(2);
Counter second = new Counter(5);
first.increment();
System.out.println(first.value());
System.out.println(second.value());
}
}Check your understanding
Two counters start independently. Predict both values after calling increment twice on the first counter.
See the example and explanation
- Example 1
- Given
first = 2, second = 5 - Answer
4, 5 - Example 2
- Given
first = 0, second = 0 - Answer
2, 0
Two increments add 2 to the first instance’s field. The second instance’s field keeps its initial value.