Encapsulation is one of the four fundamental Object-Oriented Programming (OOP) concepts. It is the mechanism of wrapping the data (variables) and the code (methods) acting on the data into a single unit, known as a class. Encapsulation helps to protect the data from unauthorized access and modification.

Key Concepts of Encapsulation

  1. Data Hiding: Encapsulation allows the internal state of an object to be hidden from the outside. Only the methods of the object can access and modify the internal state.
  2. Access Modifiers: Java provides access modifiers to control the visibility of class members. The most common access modifiers are:
    • private: The member is accessible only within the same class.
    • protected: The member is accessible within the same package and subclasses.
    • public: The member is accessible from any other class.
    • default (no modifier): The member is accessible only within the same package.
  3. Getter and Setter Methods: These methods are used to access and modify the private variables of a class. They provide a controlled way to access the data.

Practical Example

Let's create a simple class Person to demonstrate encapsulation.

public class Person {
    // Private variables
    private String name;
    private int age;

    // Constructor
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter method for name
    public String getName() {
        return name;
    }

    // Setter method for name
    public void setName(String name) {
        this.name = name;
    }

    // Getter method for age
    public int getAge() {
        return age;
    }

    // Setter method for age
    public void setAge(int age) {
        if (age > 0) { // Validation to ensure age is positive
            this.age = age;
        }
    }

    // Method to display person details
    public void displayPersonDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Explanation

  • Private Variables: The variables name and age are declared as private, meaning they cannot be accessed directly from outside the class.
  • Constructor: The constructor initializes the name and age variables.
  • Getter and Setter Methods: These methods provide a way to access and modify the private variables. The setter method for age includes a validation check to ensure the age is positive.
  • Display Method: The displayPersonDetails method prints the details of the person.

Using the Person Class

public class Main {
    public static void main(String[] args) {
        // Creating an object of Person class
        Person person = new Person("John Doe", 25);

        // Accessing and modifying the private variables using getter and setter methods
        System.out.println("Initial Details:");
        person.displayPersonDetails();

        // Modifying the name and age
        person.setName("Jane Doe");
        person.setAge(30);

        System.out.println("\nUpdated Details:");
        person.displayPersonDetails();
    }
}

Output

Initial Details:
Name: John Doe
Age: 25

Updated Details:
Name: Jane Doe
Age: 30

Practical Exercises

Exercise 1: Create a BankAccount Class

  1. Create a class BankAccount with the following private variables:
    • accountNumber (String)
    • balance (double)
  2. Provide getter and setter methods for these variables.
  3. Add a method deposit to add money to the account.
  4. Add a method withdraw to withdraw money from the account, ensuring the balance does not go negative.

Solution

public class BankAccount {
    private String accountNumber;
    private double balance;

    public BankAccount(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }

    public String getAccountNumber() {
        return accountNumber;
    }

    public void setAccountNumber(String accountNumber) {
        this.accountNumber = accountNumber;
    }

    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 void displayAccountDetails() {
        System.out.println("Account Number: " + accountNumber);
        System.out.println("Balance: " + balance);
    }
}

Using the BankAccount Class

public class Main {
    public static void main(String[] args) {
        // Creating an object of BankAccount class
        BankAccount account = new BankAccount("123456789", 1000.0);

        // Display initial account details
        System.out.println("Initial Account Details:");
        account.displayAccountDetails();

        // Deposit money
        account.deposit(500.0);
        System.out.println("\nAfter Deposit:");
        account.displayAccountDetails();

        // Withdraw money
        account.withdraw(300.0);
        System.out.println("\nAfter Withdrawal:");
        account.displayAccountDetails();
    }
}

Output

Initial Account Details:
Account Number: 123456789
Balance: 1000.0

After Deposit:
Account Number: 123456789
Balance: 1500.0

After Withdrawal:
Account Number: 123456789
Balance: 1200.0

Common Mistakes and Tips

  • Direct Access: Avoid accessing private variables directly from outside the class. Always use getter and setter methods.
  • Validation: Implement validation checks in setter methods to ensure the data is valid.
  • Encapsulation Benefits: Remember that encapsulation helps in maintaining the integrity of the data and makes the code more modular and easier to maintain.

Conclusion

Encapsulation is a powerful concept in Java that helps in protecting the data and ensuring that it is accessed and modified in a controlled manner. By using private variables and providing public getter and setter methods, you can achieve data hiding and maintain the integrity of your objects. In the next topic, we will explore the concept of abstraction, which builds upon encapsulation to provide a higher level of data hiding and interface design.

Java Programming Course

Module 1: Introduction to Java

Module 2: Control Flow

Module 3: Object-Oriented Programming

Module 4: Advanced Object-Oriented Programming

Module 5: Data Structures and Collections

Module 6: Exception Handling

Module 7: File I/O

Module 8: Multithreading and Concurrency

Module 9: Networking

Module 10: Advanced Topics

Module 11: Java Frameworks and Libraries

Module 12: Building Real-World Applications

© Copyright 2024. All rights reserved