Java Tutorial 0/145 lessons ~6 min read Lesson 19

    Encapsulation

    java encapsulation private public protected getters setters data hiding javabeans immutable validation access modifiers spring hibernate

    Course progress0%
    Focus
    22 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    In the previous lesson, you learned about Classes, Objects, Constructors, and the this keyword. These concepts form the foundation of Object-Oriented Programming (OOP).

    However, imagine the following banking application:

    java
    BankAccount account = new BankAccount();
    account.balance = -50000;

    Or consider an employee management system:

    java
    employee.salary = -100000;

    Should external code be allowed to modify important data directly?

    No.

    Allowing unrestricted access to an object's data can lead to invalid states, security issues, and maintenance problems.

    Java solves this using Encapsulation, one of the four fundamental pillars of Object-Oriented Programming.

    Encapsulation means wrapping data (fields) and methods (behavior) together into a single unit while restricting direct access to the data.

    Instead of exposing variables directly, we use private fields and provide controlled access through getter and setter methods.

    Encapsulation is heavily used in:

    • Spring Boot Applications
    • Banking Systems
    • Healthcare Software
    • Enterprise ERP Applications
    • REST APIs
    • Hibernate/JPA Entities
    • JavaBeans

    In this lesson, you'll learn:

    • What is Encapsulation?
    • Why Encapsulation is Important
    • Data Hiding
    • Access Modifiers
    • Private Fields
    • Getter Methods
    • Setter Methods
    • JavaBeans Convention
    • Validation using Setters
    • Immutable Classes
    • Encapsulation in Enterprise Applications
    • Best Practices
    • Common Mistakes
    • Hands-on Exercises
    • Professional Interview Questions

    What is Encapsulation?

    Encapsulation is the process of combining data (fields) and methods (behavior) into a single class while restricting direct access to the internal data.

    Instead of allowing direct field access:

    java
    employee.salary = -10000;

    We provide controlled methods:

    java
    employee.setSalary(50000);
    double salary = employee.getSalary();

    This ensures that invalid data cannot enter the object.

    Real-World Analogy

    Think about an ATM Machine.

    You cannot directly access the money stored inside the ATM.

    Instead, you interact through controlled operations:

    • Insert Card
    • Enter PIN
    • Withdraw Money
    • Check Balance

    The internal cash storage remains hidden.

    Similarly, in Java:

    User
    Public Methods
    Private Data

    This concept is called Data Hiding.

    Why Encapsulation?

    Without encapsulation:

    java
    class Employee {
    String name;
    double salary;
    }

    Anyone can write:

    java
    employee.salary = -50000;

    With encapsulation:

    java
    private double salary;

    Only approved methods can modify the value.

    Benefits:

    • Protects data
    • Prevents invalid object states
    • Easier maintenance
    • Better flexibility
    • Improved security
    • Supports validation
    • Promotes loose coupling

    Access Modifiers

    Java provides four access modifiers.

    ModifierSame ClassSame PackageSubclassOther Package
    private
    default
    protected✔*
    public

    * Accessible through inheritance.

    Private Fields

    Private fields cannot be accessed directly from outside the class.

    Example:

    java
    class Student {
    private String name;
    private int age;
    }

    Trying to access:

    java
    student.name = "Rahul";

    Results in:

    Compilation Error

    Getter Methods

    A getter returns the value of a private field.

    Example:

    java
    class Student {
    private String name;
    public String getName() {
    return name;
    }
    }

    Using it:

    java
    Student student = new Student();
    System.out.println(student.getName());

    Setter Methods

    A setter updates the value of a private field.

    java
    class Student {
    private String name;
    public void setName(String name) {
    this.name = name;
    }
    }

    Using it:

    java
    student.setName("Jagannath");

    Complete Encapsulation Example

    java
    class Employee {
    private String name;
    private double salary;
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public double getSalary() {
    return salary;
    }
    public void setSalary(double salary) {
    this.salary = salary;
    }
    }

    Using the class:

    java
    Employee employee = new Employee();
    employee.setName("Rahul");
    employee.setSalary(50000);
    System.out.println(employee.getName());
    System.out.println(employee.getSalary());

    Output:

    Rahul
    50000.0

    Validation Using Setters

    One major advantage of encapsulation is validation.

    Example:

    java
    class BankAccount {
    private double balance;
    public void setBalance(double balance) {
    if(balance >= 0) {
    this.balance = balance;
    }
    }
    }

    Now:

    java
    account.setBalance(-5000);

    The invalid value is rejected.

    This prevents inconsistent object states.

    JavaBeans Convention

    A JavaBean follows standard naming conventions.

    Fields:

    java
    private String firstName;

    Getter:

    java
    public String getFirstName()

    Setter:

    java
    public void setFirstName(String firstName)

    Boolean Getter:

    java
    private boolean active;
    public boolean isActive()

    Java frameworks like Spring, Hibernate, and Jackson rely heavily on these conventions.

    Read-Only Objects

    Sometimes data should be readable but not modifiable.

    Example:

    java
    class Employee {
    private String employeeId;
    public String getEmployeeId() {
    return employeeId;
    }
    }

    No setter is provided.

    The object becomes read-only for that field.

    Immutable Classes

    An immutable object cannot be modified after creation.

    Example:

    java
    public final class Employee {
    private final String employeeId;
    public Employee(String employeeId) {
    this.employeeId = employeeId;
    }
    public String getEmployeeId() {
    return employeeId;
    }
    }

    Characteristics:

    • Class is final
    • Fields are private final
    • No setters
    • Values assigned only once

    Examples from Java:

    • String
    • Wrapper Classes (Integer, Double, etc.)
    • Many classes in the java.time package

    Immutable objects are thread-safe and easier to reason about.

    Encapsulation in Enterprise Applications

    Consider a Spring Boot entity:

    java
    @Entity
    public class Customer {
    @Id
    private Long id;
    private String name;
    private double balance;
    public Long getId() {
    return id;
    }
    public void setName(String name) {
    this.name = name;
    }
    public double getBalance() {
    return balance;
    }
    public void deposit(double amount) {
    if (amount > 0) {
    balance += amount;
    }
    }
    }

    Notice that business operations (deposit) enforce rules instead of allowing direct field manipulation.

    This keeps the domain model consistent.

    Encapsulation vs Data Hiding

    EncapsulationData Hiding
    Bundles data and methods togetherRestricts direct access to data
    Achieved using classesAchieved using access modifiers
    Improves modularityImproves security
    One of the four OOP pillarsA technique used within encapsulation

    Real-World Example: Banking System

    java
    class BankAccount {
    private double balance;
    public void deposit(double amount) {
    if(amount > 0) {
    balance += amount;
    }
    }
    public void withdraw(double amount) {
    if(amount <= balance) {
    balance -= amount;
    }
    }
    public double getBalance() {
    return balance;
    }
    }

    Using it:

    java
    BankAccount account = new BankAccount();
    account.deposit(10000);
    account.withdraw(3000);
    System.out.println(account.getBalance());

    Output:

    7000.0

    Best Practices

    Keep Fields Private

    Always declare fields as private unless there is a compelling reason not to.

    Validate Input in Setters

    Never trust external input. Validate before assigning values.

    Expose Behavior, Not Just Data

    Instead of:

    java
    account.setBalance(10000);

    Prefer:

    java
    account.deposit(10000);

    This enforces business rules and improves maintainability.

    Avoid Unnecessary Setters

    If a field should never change after object creation, do not provide a setter.

    Follow JavaBeans Naming Conventions

    Use getX(), setX(), and isX() consistently to maximize framework compatibility.

    Common Mistakes

    Making All Fields Public

    Public fields break encapsulation and make validation impossible.

    Skipping Validation

    A setter without validation can still allow invalid object states.

    Exposing Mutable Objects Directly

    Returning mutable collections or objects without defensive copies can allow external modification.

    Creating Setters for Every Field

    Not every field should be editable. Design APIs based on business requirements.

    Confusing Encapsulation with Abstraction

    Encapsulation protects an object's internal state.

    Abstraction hides implementation details and exposes only essential functionality.

    Hands-on Exercise

    Create a Java program that:

    1. Creates a BankAccount class with private fields:
      • accountNumber
      • accountHolder
      • balance
    2. Generates getters for all fields.
    3. Creates setters with proper validation.
    4. Adds deposit() and withdraw() methods instead of directly modifying the balance.
    5. Prevents negative deposits and overdrafts.
    6. Makes accountNumber read-only after object creation.
    7. Creates three bank account objects and demonstrates encapsulation.

    Summary

    Encapsulation is one of the most important principles of Object-Oriented Programming. By making fields private and exposing controlled methods, developers can protect object integrity, enforce business rules, and build secure, maintainable, and scalable applications. Modern Java frameworks such as Spring Boot, Hibernate, and Jackson heavily rely on encapsulated JavaBeans.

    Key Takeaways

    • Encapsulation combines data and behavior into a single class.
    • Use private fields to hide internal data.
    • Getters provide controlled read access.
    • Setters provide controlled write access and validation.
    • JavaBeans follow standard getter/setter naming conventions.
    • Immutable classes prevent modification after creation.
    • Business operations should be exposed through methods rather than unrestricted setters.
    • Encapsulation improves security, maintainability, and flexibility.

    Professional Interview Questions

    1What is Encapsulation in Java?

    Professional Answer

    Encapsulation is the OOP principle of bundling data and the methods that operate on that data within a single class while restricting direct access to the internal state. It is typically implemented using private fields and public getter/setter methods, allowing validation and controlled access.

    Follow-up Questions

    • How is encapsulation different from data hiding?
    • Why are private fields recommended?

    Interview Tip: Emphasize that encapsulation is about both data protection and controlled access, not just making fields private.

    2Why should fields be declared private?

    Professional Answer

    Declaring fields as private prevents external classes from modifying an object's internal state directly. This allows the class to enforce validation, maintain consistency, and evolve its implementation without affecting client code.

    Follow-up Questions

    • Can private fields be accessed outside the class?
    • What is the role of getters and setters?

    Interview Tip: Private fields help preserve object integrity and reduce unintended side effects.

    3What is the difference between Encapsulation and Abstraction?

    Professional Answer

    Encapsulation focuses on protecting an object's internal state by restricting direct access and exposing controlled methods. Abstraction focuses on hiding implementation details and exposing only the essential functionality required by the user. Encapsulation is implemented using access modifiers, while abstraction is commonly achieved through abstract classes and interfaces.

    Follow-up Questions

    • Can a class demonstrate both encapsulation and abstraction?
    • Which Java features support abstraction?

    Interview Tip: A useful way to remember: Encapsulation = Protect the data, Abstraction = Hide the complexity.

    Ready to mark this lesson complete?Track your journey across the entire course.