0
0
JavaHow-ToBeginner · 3 min read

How to Achieve Encapsulation in Java: Simple Guide

Encapsulation in Java is achieved by declaring class variables as private and providing public getter and setter methods to access and modify them. This hides the internal state and protects it from unauthorized access or modification.
📐

Syntax

To achieve encapsulation, declare class variables as private to restrict direct access. Then, provide public methods called getters and setters to read and update these variables safely.

  • private keyword hides the variable from outside classes.
  • public getter method returns the variable's value.
  • public setter method updates the variable's value.
java
public class Person {
    private String name;  // private variable

    // public getter method
    public String getName() {
        return name;
    }

    // public setter method
    public void setName(String newName) {
        this.name = newName;
    }
}
💻

Example

This example shows a Person class with a private age field. The public getter and setter control access to age. The setter also checks that age is not negative, demonstrating data protection.

java
public class Person {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        } else {
            System.out.println("Age cannot be negative.");
        }
    }

    public static void main(String[] args) {
        Person p = new Person();
        p.setAge(25);
        System.out.println("Age: " + p.getAge());
        p.setAge(-5);  // tries to set invalid age
        System.out.println("Age after invalid set: " + p.getAge());
    }
}
Output
Age: 25 Age cannot be negative. Age after invalid set: 25
⚠️

Common Pitfalls

Common mistakes when using encapsulation include:

  • Making variables public which breaks encapsulation.
  • Not using getters/setters, so no control over data changes.
  • Setter methods that do not validate input, allowing invalid data.

Always keep variables private and use getters/setters with validation if needed.

java
public class Wrong {
    public int data;  // public variable - bad practice
}

public class Right {
    private int data;

    public int getData() {
        return data;
    }

    public void setData(int data) {
        if (data >= 0) {
            this.data = data;
        }
    }
}
📊

Quick Reference

Encapsulation Cheat Sheet:

ConceptDescription
private variablesHide data from outside classes
public gettersAllow read access to private variables
public settersAllow controlled write access with validation
data validationProtect data integrity inside setters
no direct accessPrevent external code from changing variables directly

Key Takeaways

Use private fields to hide class data from outside access.
Provide public getter and setter methods to control data access.
Add validation inside setters to protect data integrity.
Avoid making variables public to maintain encapsulation.
Encapsulation improves code safety and maintainability.