Encapsulation and Data Hiding

Loading

Encapsulation and Data Hiding are fundamental concepts in Object-Oriented Programming (OOP) that help in organizing and protecting the data within a class. Encapsulation is the mechanism of wrapping data (variables) and code (methods) together as a single unit, while data hiding restricts direct access to some of an object’s components, ensuring that the internal representation of an object is hidden from the outside world.


1. Encapsulation

Encapsulation is the bundling of data (attributes) and methods (behaviors) that operate on the data into a single unit, typically a class. It also controls the access to the data, ensuring that it can only be accessed or modified through well-defined methods.

Key Points:

  • Combines data and methods into a single unit (class).
  • Protects the integrity of the data by controlling access to it.
  • Improves code maintainability and reusability.

Example:

class Person {
    // Private fields (data hiding)
    private String name;
    private int age;

    // Public getter and setter methods (encapsulation)
    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) { // Validation
            this.age = age;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        person.setAge(25);
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

2. Data Hiding

Data hiding is a technique used to restrict direct access to an object’s data members (fields). It ensures that the internal representation of an object is hidden from the outside world and can only be accessed or modified through methods.

Key Points:

  • Achieved using access modifiers (private, protected, public).
  • Prevents unauthorized access and modification of data.
  • Ensures data integrity and security.

Example:

class BankAccount {
    // Private fields (data hiding)
    private double balance;

    // Public methods to access and modify the balance (encapsulation)
    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;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        account.deposit(1000);
        account.withdraw(500);
        System.out.println("Balance: " + account.getBalance());
    }
}

3. Access Modifiers

Access modifiers control the visibility of fields, methods, and classes. They are essential for implementing encapsulation and data hiding.

Access ModifierVisibility
privateAccessible only within the class.
protectedAccessible within the same package and subclasses.
publicAccessible from anywhere.
DefaultAccessible within the same package (no modifier).

4. Benefits of Encapsulation and Data Hiding

  1. Data Integrity: Ensures that data is valid and consistent by controlling access to it.
  2. Security: Prevents unauthorized access and modification of data.
  3. Flexibility: Allows the internal implementation of a class to change without affecting other parts of the program.
  4. Reusability: Encapsulated classes can be reused in different parts of the program or in other programs.
  5. Maintainability: Improves code readability and maintainability by organizing related data and methods together.

5. Example Program

class Employee {
    // Private fields (data hiding)
    private String name;
    private double salary;

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

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

    public double getSalary() {
        return salary;
    }

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

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();
        emp.setName("Alice");
        emp.setSalary(50000);
        System.out.println("Name: " + emp.getName());
        System.out.println("Salary: " + emp.getSalary());
    }
}

6. Summary

ConceptDescription
EncapsulationBundling data and methods into a single unit (class).
Data HidingRestricting direct access to an object’s data members.
Access ModifiersControl the visibility of fields, methods, and classes.
Getters and SettersMethods used to access and modify private fields.
BenefitsData integrity, security, flexibility, reusability, and maintainability.

Encapsulation and data hiding are essential for writing secure, maintainable, and reusable Java programs. They help in organizing code and protecting data from unauthorized access and modification.

Leave a Reply

Your email address will not be published. Required fields are marked *