Encapsulation and Access Control
Explore how encapsulation safeguards object data in Java by using private access modifiers and public getter and setter methods. Understand how these controls prevent invalid state changes and promote reliable, maintainable code. This lesson helps you design well-encapsulated classes, balancing data hiding with controlled access to keep objects safe and consistent.
Imagine a robot. We do not interact with its internal wires or battery cells directly. Instead, we use a control panel or specific buttons to give it commands. This outer casing protects the delicate internals from damage and ensures we don't accidentally short-circuit the system.
In Java, objects also need protection. Allowing any part of the code to modify an object's internal data directly can put it in an invalid state. For example, setting a robot's battery level to -50%. Encapsulation bundles data with protection mechanisms, ensuring objects stay safe, predictable, and valid.
The problem with uncontrolled access
Previously, we defined classes with public fields. While this is simple, it is also dangerous because it gives the outside world unrestricted access to modify an object's state.
Let's look at a Robot class that stores a battery level. Since the field is public, nothing stops us from assigning a nonsensical value.
For convenience, we are defining our class and our main method in the same file so you can see the code usage easily.
Lines 1–3: We define a
Robotclass with apublicinteger field namedbatteryLevel.Line 9: Because
batteryLevelis public, themainmethod accesses it directly and assigns ...