WikiGalaxy

Personalize

Java Encapsulation

Introduction to Encapsulation:

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. It helps in protecting the data from outside interference and misuse.

Benefits of Encapsulation:

Encapsulation helps in data hiding, improves modularity, and allows for a flexible and maintainable code structure. It also enhances security by restricting access to the internal state of an object.


public class Student {
    private String name;
    private int age;

    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;
        }
    }
}
    

Console Output:

No direct console output. Encapsulation is a design concept.

Data Hiding with Encapsulation

Data Hiding:

In encapsulation, the variables of a class are hidden from other classes and can be accessed only through the methods of their current class. This is known as data hiding.

Why Data Hiding?

Data hiding ensures controlled access to the class members, which reduces the risk of data corruption and misuse by external classes.


class Account {
    private double balance;

    public double getBalance() {
        return balance;
    }

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

Console Output:

No direct console output. Data hiding is a design principle.

Encapsulation in Action

Encapsulation Example:

By using private fields and providing public getter and setter methods, we can control the access and modification of the fields’ values, ensuring encapsulation.

Secure Access:

This approach secures the data from unauthorized access and provides a controlled way to modify it.


class Employee {
    private String empId;
    private double salary;

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId = empId;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        if(salary > 0) {
            this.salary = salary;
        }
    }
}
    

Console Output:

No direct console output. Encapsulation is implemented in code design.

Encapsulation and Access Modifiers

Role of Access Modifiers:

Access modifiers in Java play a crucial role in encapsulation. They define the scope of access to the class members.

Common Modifiers:

The most common access modifiers are public, private, protected, and default, each serving a different level of access control.


class Car {
    private String model;
    private int year;

    public String getModel() {
        return model;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        if(year > 1885) { // The first car was invented around 1885
            this.year = year;
        }
    }
}
    

Console Output:

No direct console output. Access modifiers control access levels.

Encapsulation and Abstraction

Relationship with Abstraction:

Encapsulation and abstraction are both fundamental OOP concepts. While encapsulation is about hiding the internal state, abstraction focuses on exposing only essential features.

Unified Design:

Together, they help in creating a clear separation between the interface and implementation, enhancing code readability and maintainability.


abstract class Animal {
    private String name;

    public String getName() {
        return name;
    }

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

    abstract void makeSound();
}
    

Console Output:

No direct console output. Encapsulation and abstraction work together.

Encapsulation in Real-World Applications

Practical Usage:

Encapsulation is widely used in real-world applications to protect sensitive data and ensure that objects are used correctly.

Example in Banking:

In banking systems, encapsulation is used to protect customer data and ensure secure transactions.


class BankAccount {
    private String accountNumber;
    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 > 0 && amount <= balance) {
            balance -= amount;
        }
    }
}
    

Console Output:

No direct console output. Encapsulation secures banking operations.

Encapsulation and Inheritance

Working with Inheritance:

Encapsulation works seamlessly with inheritance by allowing subclasses to inherit methods and fields while still controlling access through access modifiers.

Controlled Inheritance:

This controlled access ensures that subclasses use the inherited features correctly without exposing or altering the encapsulated data.


class Vehicle {
    private String type;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

class Car extends Vehicle {
    private int doors;

    public int getDoors() {
        return doors;
    }

    public void setDoors(int doors) {
        this.doors = doors;
    }
}
    

Console Output:

No direct console output. Encapsulation aids inheritance design.

Encapsulation and Polymorphism

Encapsulation Supports Polymorphism:

Encapsulation ensures that a method or a variable can be used polymorphically while maintaining the integrity of the encapsulated data.

Dynamic Method Binding:

Polymorphism allows for dynamic method binding, where the method to be invoked is determined at runtime, supporting flexible and reusable code.


interface Shape {
    void draw();
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Drawing a circle");
    }
}

class Square implements Shape {
    public void draw() {
        System.out.println("Drawing a square");
    }
}
    

Console Output:

Drawing a circle
Drawing a square

Encapsulation and Interface

Encapsulation with Interfaces:

Interfaces in Java provide a way to achieve abstraction and encapsulation by defining a contract that classes must follow, ensuring a consistent structure.

Interface Implementation:

Classes implementing an interface must provide concrete implementations for all methods declared in the interface, promoting encapsulation by restricting access to implementation details.


interface Vehicle {
    void start();
    void stop();
}

class Bike implements Vehicle {
    public void start() {
        System.out.println("Bike started");
    }

    public void stop() {
        System.out.println("Bike stopped");
    }
}
    

Console Output:

Bike started
Bike stopped

Encapsulation in Java Libraries

Encapsulation in Libraries:

Java libraries extensively use encapsulation to provide a clean and easy-to-use API while hiding complex implementation details.

Example in Collections:

The Java Collections Framework uses encapsulation to manage data structures like lists, sets, and maps, providing methods to interact with them without exposing their internal workings.


import java.util.ArrayList;
import java.util.List;

public class LibraryExample {
    public static void main(String[] args) {
        List books = new ArrayList<>();
        books.add("Java Programming");
        books.add("Effective Java");

        for(String book : books) {
            System.out.println(book);
        }
    }
}
    

Console Output:

Java Programming
Effective Java

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025