CodeToConcept
About

java

java Tutorials

Introduction
Java Fundamentals
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Control Statements
Java Class & Object
java Method
Java Constructor
Java this keyword
OOP Principles
Java super keyword
Coming Soon Topics

java Tutorials

Introduction
Java Fundamentals
Java Variables
Java Data Types
Java Type Casting
Java Operators
Java Input/Output
Control Statements
Java Class & Object
java Method
Java Constructor
Java this keyword
OOP Principles
Java super keyword
Coming Soon Topics

Sample Question

Think it through, then check the tutorial.

CodeToConcept

Quickly learn through simple, structured, and practical coding tutorials. Build your confidence from step zero to real-world experience.

Β© 2026 CodeToConcept. All rights reserved.

Quick Links

AboutTutorials

Tutorials

Java

Support

Privacy PolicyTerms of ServiceContact
GitHubTwitterYouTube

Encapsulation in Java

Encapsulation, as the name suggests, means "capsuling" or wrapping something, so here we are wrapping the variables and methods into a single unit called a class. That is, we are binding data and methods together into a single unit.

We can achieve this in Java by making the members private and providing publicly available methods to access those private members while maintaining full control over how they are accessed.

So we can say Encapsulation = Data Hiding + Controlled Access

Example:

public class HelloWorld {
 
     public static void main(String[] args){
 
        BankAccount account = new BankAccount();
        account.deposit(500);
        System.out.println(account.getBalance()); // 500
     }
}
 
class BankAccount {
    private double balance;  // hidden data, that is not directly accessible from outside the class
 
    // public methods to access the private data (controlled access)
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
 
    // public methods to access the private data (controlled access)
    public double getBalance() {
        return balance;
    }
}

Explanation:

So here balance is private and cannot be changed directly from outside the class. The publicly available methods deposit() and getBalance() provide controlled access to balance.

Advantages of Encapsulation:

1. Reduces the risk of accidental data alteration

Encapsulation prevents direct access to object data. otherwise, anyone could modify it, resulting in incorrect or inconsistent data.

Example:

public class HelloWorld {
    public static void main(String[] args) {
        Student student = new Student();
        
        student.age = -10;  //direct modification of data
        System.out.println(student.age);// output: -10
    }
}
 
class Student {
    public int age;
}

So here the age of the student can be directly modified from outside the class, which can lead to incorrect or inconsistent data. This demonstrates the risk of not using encapsulation.

2. Improves security

Encapsulation helps to enhances security by restricting direct access to sensitive data. So we can make a class read-only or write-only by controlling access using getter and setter methods.

Example:

public class HelloWorld {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
 
        account.deposit(5000);
        account.withdraw(1000);
 
        System.out.println("Balance: " + account.getBalance());
 
        // account.balance = 100000; // here direct access to sensitive data is not possible.(compile time error)
 
    }
}
 
class BankAccount {
    private double balance;  // Sensitive data
 
    // public methods to access the private data (controlled access)
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }
 
    // public methods to access the private data (controlled access)
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }
 
    // public methods to access the private data (controlled access)
    public double getBalance() {
        return balance;
    }
}
Making Read-Only Class:

Example:

public class HelloWorld {
    public static void main(String[] args) {
        Student s = new Student();
 
        System.out.println(s.getName());
        System.out.println(s.getAge());
 
        // s.name = "Mike"; So here direct modification of data is ❌ not allowed (as it is private variable)
        // No setter available, so values cannot be set or updated
    }
}
 
class Student {
    private String name = "John";
    private int age = 20;
 
    public String getName() {
        return name;
    }
 
    public int getAge() {
        return age;
    }
}
Making Write-Only Class:

Example:

public class HelloWorld {
    public static void main(String[] args) {
        Employee e = new Employee();
 
        e.setPassword("mySecret123");
 
        // System.out.println(e.password); ❌ Not allowed
        // No getter available, so value cannot be read
    }
}
 
class Employee {
    private String password;
 
    public void setPassword(String password) {
        this.password = password;
    }
}
3. Improves Maintainability.

It organizes the code properly, and any changes in the internal implementation do not affect external usage.

Example:

 
public class HelloWorld {
    public static void main(String[] args) {
       Student s = new Student();
       s.setName("Ashish");
       System.out.println(s.getName());
 
    }
}
 
//This is the initial implementation of student class.
class Student {
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

After updating the implementation.

 
public class HelloWorld {
    public static void main(String[] args) {
       Student s = new Student();
       s.setName("Ashish");
       System.out.println(s.getName());
 
    }
}
 
class Student {
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name.toUpperCase();// Here the internal implementation is updated to store the name in uppercase
        //but the external usage remains the same, so other parts of the program are not affected
    }
}

So here the users access the data through methods (getName() and setName()), and changes to the internal implementation do not affect other parts of the program.

See you in next page....πŸ™‚

← Java this keywordJava Inheritance β†’
← Java this keywordJava Inheritance β†’