Java ProgramsOOPEncapsulation

Encapsulation in Java

beginner·  OOP  ·  Encapsulation

Problem

Encapsulation means hiding a class's fields behind private access and only exposing controlled ways to read or change them, so invalid state can be rejected before it's ever stored.

Define an Employee class with a private salary field that rejects a negative value when set.

Input
setSalary(-500.0), setSalary(50000.0)
Output
Rejected: salary cannot be negative Salary: 50000.0

Java Program

Java
class Employee { private double salary; void setSalary(double salary) { if (salary < 0) { // reject invalid state before it's ever stored System.out.println("Rejected: salary cannot be negative"); return; } this.salary = salary; } double getSalary() { return salary; } } public class EncapsulationDemo { public static void main(String[] args) { Employee emp = new Employee(); emp.setSalary(-500.0); emp.setSalary(50000.0); System.out.println("Salary: " + emp.getSalary()); } }

Output

Rejected: salary cannot be negative Salary: 50000.0

Core Logic

Making salary private and only reachable through setSalary() means every attempt to change it passes through a validation check first, something a public field could never enforce.

How It Works
  1. 1private double salary; can't be read or written directly from outside Employeeemp.salary = -500.0; wouldn't even compile.
  2. 2setSalary(double salary) checks salary < 0 before storing anything, rejecting the invalid value instead of accepting it.
  3. 3The first call, setSalary(-500.0), is rejected and salary keeps its default value of 0.0.
  4. 4The second call, setSalary(50000.0), passes the check and actually updates the field.
After both calls, getSalary() returns 50000.0 — the negative attempt never touched the field at all.
💡

Key Point: If salary had been a public field instead, nothing would have stopped code elsewhere from setting it directly to a negative value — encapsulation is what makes the validation actually enforceable. This is the why behind hiding fields; Getter and Setter covers the specific accessor/mutator naming convention on its own.

Key Concepts

private fieldvalidationdata hiding

Related Programs