Tutorials Logic, IN info@tutorialslogic.com

Encapsulation in Java Access Modifiers

Encapsulation with Validation

Getters and setters are useful only when they preserve a rule; exposing every field mechanically does not create meaningful encapsulation.

Encapsulation is not only about making fields private. It is about protecting object state so that every object remains valid after construction and after every method call.

In project code, encapsulation protects future changes. If outside code touches fields directly, changing validation or storage becomes difficult. If outside code uses methods, the class can improve its internal rules without breaking callers.

Encapsulation also improves debugging because every state change passes through a small number of methods. If a value becomes invalid, you know exactly which setters or constructors to inspect.

Test invalid updates as well as valid ones to prove that an object cannot enter a state its public contract forbids.

A class should decide which data can be changed and how it can be changed. Private fields prevent outside code from directly setting unsafe values, while public methods provide controlled access.

Good setters validate input before assigning it. In many real projects, immutable classes with final fields and constructor validation are even safer than many setters.

  • Keep fields private unless there is a strong reason not to.
  • Expose behavior, not raw internal storage.
  • Validate values before changing object state.
  • Avoid getters that expose mutable internal collections directly.

Protecting object state with encapsulation

Encapsulation keeps object data behind a controlled public API. Instead of allowing any code to change fields directly, a class can validate changes through methods. This protects important rules such as balance cannot be negative, email must be valid, or marks must stay between 0 and 100.

Private fields alone are not the full lesson. The real point is that the object should be responsible for keeping itself valid. Getters and setters are useful when they preserve that responsibility, but blindly generating them for every field can still expose the object too much.

  • Use methods to enforce valid state changes.
  • Avoid setters that allow impossible or unsafe values.
  • Name methods around behavior when possible, such as deposit() instead of setBalance().

Encapsulation in Java Access Modifiers Example

Encapsulation in Java Access Modifiers Example
public class Demo {
    public static void main(String[] args) {
        System.out.println("Practice Encapsulation in Java Access Modifiers");
    }
}

Encapsulated Student Object

Encapsulated Student Object
class Student {
    private String name;
    private int marks;

    Student(String name, int marks) {
        setName(name);
        setMarks(marks);
    }

    public void setName(String name) {
        if (name == null || name.isBlank()) {
            throw new IllegalArgumentException("name is required");
        }
        this.name = name;
    }

    public void setMarks(int marks) {
        if (marks < 0 || marks > 100) {
            throw new IllegalArgumentException("marks must be 0 to 100");
        }
        this.marks = marks;
    }
}

Bank account with controlled balance changes

Bank account with controlled balance changes
class BankAccount {
    private double balance;

    void deposit(double amount) {
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        balance += amount;
    }

    double getBalance() { return balance; }
}
Before you move on

Encapsulation in Java Access Modifiers Mastery Check

5 checks
  • A class should decide which data can be changed and how it can be changed.
  • Private fields prevent outside code from directly setting unsafe values, while public methods provide controlled access.
  • Good setters validate input before assigning it.
  • In many real projects, immutable classes with final fields and constructor validation are even safer than many setters.
  • Encapsulation keeps object data behind a controlled public API.

Encapsulation in Java Access Modifiers Questions Learners Ask

No. Expose meaningful operations and keep fields hidden when direct changes would break object rules.

Access from the same package and from subclasses, subject to Java access rules.

It prevents the object from entering an invalid state.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.