← Back to list

OOP in Java: Encapsulation.

Why letting other code touch your fields directly is a bad idea.

Deep Shah · 2026-06-08 04:23 · 51 claps · 4.7 min read
#java #object-oriented #oops-concepts #automation #coding
Open on Medium ↗
Wiki topics: 💻 · Programming

OOP in Java: Encapsulation.

Why letting other code touch your fields directly is a bad idea.

You built a class. It works. Then someone sets a field to -500 and everything breaks. Encapsulation is the concept that prevents exactly this from happening.

OOP in Java Series Part 1: Classes and Objects — the foundation Part 2: Encapsulation — protecting your data (this article) Part 3: Inheritance — reusing code the right way Part 4: Polymorphism — one name, many forms Part 5: Abstraction — hiding what does not matter Part 6: OOP in real SDET code — how it all connects

In Part 1, we built a Car class with fields for colour, model, and fuel level. We created objects and set values on them directly. It worked perfectly for a simple example.

Now imagine a real system. Your Car class is used in ten different places across your codebase. One developer writes myCar.fuelLevel = -500. Another writes myCar.fuelLevel = 99999. Your car object now has an impossible fuel level. Nobody catches it because Java did not stop it. The class allowed it.

This is the problem encapsulation solves. It controls who can access your data and what values are allowed. Without it, your objects are completely unprotected.

Have you ever seen a bug where an object ended up with a value that should have been impossible — a negative age, a blank username, a price of zero? That is almost always an encapsulation problem.

The idea

What encapsulation actually means

Encapsulation means bundling your data and the rules for accessing that data together inside the class. The outside world does not get direct access to your fields. Instead it goes through methods that you control.

Think about a car’s fuel tank. You cannot pour fuel directly into the engine. You go through a designated fuel cap. The fuel cap is the controlled access point. It accepts the right type of fuel, in the right quantity, through the right process. Your class methods work the same way.

Two parts to encapsulation

First, make your fields private so nothing outside the class can touch them directly. Second, provide public methods that allow controlled access. Those methods are called getters and setters.

The problem What happens without encapsulation

Here is the Car class from Part 1. Every field is public, meaning any code anywhere can read or write them without restriction.

public class Car {

    // public fields — anyone can change these directly
    public String colour;
    public String model;
    public int fuelLevel;
}

// This compiles and runs with no errors
Car myCar = new Car("Red", "Swift", 50);
myCar.fuelLevel = -500;   // impossible value, Java allows it
myCar.fuelLevel = 99999;  // tank overflow, Java allows it
myCar.model = "";          // empty model name, Java allows it
myCar.colour = null;       // null colour, Java allows it

Java does not know what a valid fuel level is. You do. But with public fields, there is no place to put that knowledge. The class has no way to enforce its own rules.

The fix Private fields and public methods

The fix is straightforward. Mark every field as private. Then write methods that let outside code read and write those fields in a controlled way. These methods are called getters and setters.

public class Car {

    // private fields — nothing outside this class can touch these
    private String colour;
    private String model;
    private int fuelLevel;

    // constructor
    public Car(String colour, String model, int fuelLevel) {
        this.colour = colour;
        this.model = model;
        setFuelLevel(fuelLevel); // use the setter even here
    }

    // getter — read the value
    public String getColour() {
        return colour;
    }

    // getter
    public String getModel() {
        return model;
    }

    // getter
    public int getFuelLevel() {
        return fuelLevel;
    }

    // setter with validation — this is where the rules live
    public void setFuelLevel(int fuelLevel) {
        if (fuelLevel < 0) {
            System.out.println("Fuel level cannot be negative. Setting to 0.");
            this.fuelLevel = 0;
        } else if (fuelLevel > 100) {
            System.out.println("Fuel level cannot exceed 100. Setting to 100.");
            this.fuelLevel = 100;
        } else {
            this.fuelLevel = fuelLevel;
        }
    }

    // setter with validation
    public void setModel(String model) {
        if (model == null || model.trim().isEmpty()) {
            System.out.println("Model name cannot be empty.");
        } else {
            this.model = model;
        }
    }
}

Now the impossible values are blocked. Try to set fuel to -500 and the setter catches it. Try to set an empty model name and the setter rejects it. The rules live inside the class where they belong.

Using the class How it looks from the outside

Car myCar = new Car("Red", "Swift", 50);

// reading values through getters
System.out.println(myCar.getModel());     // Swift
System.out.println(myCar.getFuelLevel()); // 50

// valid update goes through
myCar.setFuelLevel(75);
System.out.println(myCar.getFuelLevel()); // 75

// invalid update is caught by the setter
myCar.setFuelLevel(-500);
// prints: Fuel level cannot be negative. Setting to 0.
System.out.println(myCar.getFuelLevel()); // 0

// this line no longer compiles — field is private
// myCar.fuelLevel = -500; // compile error

The compile error is a feature, not a problem

When you make a field private, any code that was accessing it directly will immediately show a compile error. That is encapsulation doing its job. It forces every access through the controlled path you defined. Fix those compile errors by replacing direct field access with the appropriate getter or setter.

Read-only fields Getters without setters

Not every field needs a setter. Some data should be set once and never changed after that. You make it read-only by providing a getter but no setter.

public class Car {

    private final String registrationNumber; // set once, never changes
    private String colour;
    private int fuelLevel;

    public Car(String regNumber, String colour, int fuelLevel) {
        this.registrationNumber = regNumber;
        this.colour = colour;
        this.fuelLevel = fuelLevel;
    }

    // getter only — no setter means nobody can change it after creation
    public String getRegistrationNumber() {
        return registrationNumber;
    }
}

A registration number does not change once a car is registered. Making the field final and providing only a getter enforces that rule at the code level. Nobody can accidentally change it later.

Encapsulation is not about hiding code for the sake of it. It is about putting rules where they can actually be enforced. The field does not know what a valid value is. The setter does. So the setter is where the check belongs.

Make your fields private. Write getters for reading. Write setters with validation for writing. Provide only what outside code genuinely needs. That is encapsulation in practice.

How are you currently handling validation in your Java projects? Do you check values before setting them, or does your code trust that whatever gets passed in is valid? Share your approach below.

Next: OOP in Java — Inheritance

Part 3 covers inheritance. How to build a new class from an existing one, what gets inherited and what does not, and why inheritance in your Selenium framework saves you from writing the same setup code in every test class.

Resources

If this article helped you, consider clapping and following for more practical SDET content.

Connect

*LinkedIn*

*GitHub*

*Instagram*

Java#OOP#Encapsulation#JavaBeginner#ObjectOrientedProgramming #CoreJava#Programming#SDET#LearnJava#SoftwareEngineering


메타데이터
post_id
d5bb09957d02
slug
oop-in-java-encapsulation-d5bb09957d02
url
https://medium.com/@deepshah201/oop-in-java-encapsulation-d5bb09957d02
canonical_url
https://medium.com/@deepshah201/oop-in-java-encapsulation-d5bb09957d02
author_url
https://medium.com/@deepshah201
status
ok
fetched_at
2026-06-23 17:05:31