Search⌘ K
AI Features

Encapsulation and Access Control

Explore encapsulation and access control in Java to safeguard object data. Understand how private fields and public getters and setters ensure objects maintain valid states and controlled interactions, enabling robust and maintainable class design.

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.

Java 25
class Robot {
// Public field: accessible by anyone
public int batteryLevel;
}
public class Main {
public static void main(String[] args) {
Robot bot = new Robot();
// We can assign a negative battery level directly
bot.batteryLevel = -50;
System.out.println("Battery Level: " + bot.batteryLevel + "%");
}
}
  • Lines 1–3: We define a Robot class with a public integer field named batteryLevel.

  • Line 9: Because batteryLevel is public, the main method accesses it directly and assigns ...