C

Core Java tutorial for beginners

Clean • Professional

Java - Encapsulation and Access Modifiers (With Real-World Examples)

6 minute

Encapsulation and Access Modifiers in Java

Encapsulation is one of the four pillars of Object-Oriented Programming (OOP) in Java — along with inheritance, polymorphism, and abstraction.

It is a core concept that helps in protecting data and keeping your code clean, secure, and maintainable.


What is Encapsulation?

Encapsulation means binding data (variables) and methods (functions) that operate on that data into a single unit — a class.

In simple words:

Encapsulation = Data Hiding + Controlled Access

This ensures that sensitive data is not directly accessed by outside code — only through public methods (getters and setters).


Example of Encapsulation

class Student {
    // Private data - cannot be accessed directly
    private String name;
    private int age;

    // Public getter and setter methods
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if(age > 0) {
            this.age = age;
        } else {
            System.out.println("Invalid age!");
        }
    }
}

public class EncapsulationExample {
    public static void main(String[] args) {
        Student s = new Student();
        s.setName("Alice");
        s.setAge(20);

        System.out.println("Name: " + s.getName());
        System.out.println("Age: " + s.getAge());
    }
}

Output:

Name: Alice
Age: 20

Why Use Encapsulation?

learn code with durgesh images

BenefitDescription
Data HidingPrevents direct access to sensitive data.
Code ControlProvides controlled access using getter and setter methods.
Improved SecurityProtects object integrity by validating data.
ReusabilityEasier to maintain and reuse code.
FlexibilityYou can change internal implementation without affecting other classes.

Access Modifiers in Java

Access modifiers control the visibility or accessibility of classes, methods, and variables.

There are four main access levels in Java:

ModifierScope / VisibilityCan Access From
privateWithin the same class onlyOnly inside the class
default (no keyword)Within the same packageClasses in same package
protectedSame package + subclasses (even in other packages)Package + inheritance
publicAccessible from anywhereAll classes everywhere

Example of Access Modifiers

package mypackage;

public class Person {
    private String name;       // Accessible only within Person class
    int age;                   // Default access
    protected String address;  // Accessible in subclasses
    public String email;       // Accessible everywhere

    public void display() {
        System.out.println("Name: " + name);
    }
}
package otherpackage;

import mypackage.Person;

public class AccessExample extends Person {
    public void showAccess() {
        // name →  private (not accessible)
        // age →  default (different package)
        System.out.println(address); //  protected
        System.out.println(email);   //  public
    }
}

Encapsulation + Access Modifiers = Data Security

By combining encapsulation and access modifiers, you can:

  • Keep your data private
  • Allow controlled access through public methods
  • Prevent accidental or unauthorized modification

Example:

class BankAccount {
    private double balance;

    public double getBalance() {
        return balance;
    }

    public void deposit(double amount) {
        if (amount > 0) balance += amount;
    }

    public void withdraw(double amount) {
        if (amount <= balance) balance -= amount;
        else System.out.println("Insufficient funds!");
    }
}

Getters and Setters in Encapsulation

Encapsulation in Java means hiding the internal data of a class and providing controlled access to it through getter and setter methods — commonly known as get() and set() methods.

These methods act like a protective layer between your class fields (data) and the outside world.


What Are Getters and Setters?

Method TypePurposeTypical Naming
GetterReads or returns the value of a private fieldgetFieldName()
SetterUpdates or modifies the value of a private fieldsetFieldName(value)
  • Getters → only read data.
  • Setterswrite or update data, often with validation.

Example: Getters and Setters in Action

class Student {
    // Step 1: Private variables (data hiding)
    private String name;
    private int age;

    // Step 2: Public getter method (to access private data)
    public String getName() {
        return name;
    }

    // Step 3: Public setter method (to modify private data)
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0) { // basic validation
            this.age = age;
        } else {
            System.out.println("Invalid age!");
        }
    }
}

public class GetterSetterExample {
    public static void main(String[] args) {
        Student s = new Student();

        s.setName("Aman");
        s.setAge(22);

        System.out.println("Name: " + s.getName());
        System.out.println("Age: " + s.getAge());
    }
}

Output:

Name: Aman
Age: 22

Why Use Getters and Setters?

ReasonExplanation
Data HidingPrevents direct modification of variables from outside.
ValidationYou can check values before setting (e.g., age > 0).
FlexibilityAllows changes in implementation without affecting other code.
Read-Only / Write-Only AccessYou can choose to expose only getter or setter based on need.

Example – Read-Only and Write-Only Fields

Read-Only Field (Only Getter):

class Config {
    private final String version = "1.0";

    public String getVersion() {
        return version;
    }
}

Write-Only Field (Only Setter):

class Password {
    private String secret;

    public void setSecret(String secret) {
        this.secret = secret;
    }
}

Points to Remember

  • Encapsulation binds data and code together.
  • Always declare variables as private and provide public getters/setters.
  • Use access modifiers to define the visibility of classes and members.
  • Data hiding improves security and reduces errors.
  • Common real-world use: Banking, employee data, user authentication systems, etc.
Article 0 of 0