Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Implementing Encapsulation in Java

In this lesson, you will learn

  • Encapsulation in Java
  • Examples

 

Encapsulation in Java

  • Encapsulation in Java is one of the four fundamental principles of object-oriented programming (OOP).
  • It involves bundling data (fields) and the methods that operate on that data within a single unit is called the class.

Encapsulation

  • It also involves controlling the access to the internal data of an object, preventing direct and inappropriate modification from outside the object.
  • This helps to protect the integrity of the data and makes the code more maintainable and less prone to errors.

Encapsulation1

Key Aspects of Encapsulation:

  1. Bundling: Combining data (instance variables) and methods (that operate on that data) into a class.

  2. Data Hiding: Making the instance variables of a class private (using the private access modifier). This prevents direct access to the variables from outside the class.

  3. Access Control: Providing public methods (getters and setters) to access and modify the private instance variables. This allows controlled access to the data.

     

    How to Implement Encapsulation in Java

    The following are the steps to implement the encapsulation in java.

    EncapsulationImplementation

    1. Declare Instance Variables as private: This is the most important step. Making the fields private prevents direct access from outside the class.

    2. Provide Public Getter Methods: Getter methods (also called accessor methods) are used to retrieve the values of the private instance variables. They typically have a name like getVariableName().

    3. Provide Public Setter Methods: Setter methods (also called mutator methods) are used to modify the values of the private instance variables. They typically have a name like setVariableName(). You can add validation or logic within the setter methods to control how the data is modified.

     

      Example 1: Understanding Encapsulation

      package ch9;
      
      class Person {
          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) { // Validation: Age cannot be negative
                  this.age = age;
              } else {
                  System.out.println("Invalid age.");
              }
          }
      }
      
      public class EncapsulationExample1 {
          public static void main(String[] args) {
              Person person = new Person();
              person.setName("Alice");
              person.setAge(30);
      
              System.out.print("Name: " + person.getName());
              System.out.println(", Age: " + person.getAge());
      
              person.setAge(-5); // This will print "Invalid age."
          }
      }
      

      Output

      Name: John, Age: 30
      

       

      Explanation

      • The Person class has two private variables: name and age.
      • It has public setName and setAge methods to modify the values of name and age, respectively. This is an example of write properties.
      • It also has public getName and getAge methods to read the values of name and age, respectively. This is an example of read properties.

       

      Through encapsulation, the actual representation of internal state is hidden from the outside, only allowing access through these public methods.

      This way, you can ensure that Person objects are always in a consistent state and protect their internal data from unauthorized access.

       

      Example 2- Bank Account Example

      class BankAccount {
          private double balance;
      
          public void setBalance(double initialBalance) {
              balance = initialBalance;
          }
      
          public double getBalance() {
              return balance;
          }
      
          public void deposit(double amount) {
              if (amount > 0) {
                  balance += amount;
              } else {
                  System.out.println("Invalid deposit amount.");
              }
          }
      
          public void withdraw(double amount) {
              if (amount > 0 && amount <= balance) {
                  balance -= amount;
              } else {
                  System.out.println("Insufficient funds or invalid withdrawal amount.");
              }
          }
      }
      
      public class EncapsulationExample2 {
          public static void main(String[] args) {
              BankAccount account = new BankAccount(1000);
              account.deposit(500);
              account.withdraw(2000); // This will print "Insufficient funds..."
              System.out.println("Balance: " + account.getBalance());
          }
      }
      
      
      

      Here, balance is private. deposit() and withdraw() methods control how the balance is changed, ensuring that only valid operations are performed.

      Benefits of Encapsulation:

      • Data Protection: Prevents accidental or intentional corruption of data.
      • Code Maintainability: Makes it easier to change the internal implementation of a class without affecting other parts of the code.
      • Code Reusability: Classes with well-defined interfaces (getters and setters) can be easily reused in other programs.
      • Abstraction: Hides the complex implementation details from the user, providing a simpler interface to interact with the object.

      Encapsulation is a crucial concept in OOP, promoting well-structured, robust, and maintainable code. It’s a best practice to always make instance variables private and provide public getter and setter methods to control access to them.

       

      Exercises: Solve Using Encapsulation

      Problem Statement 1: Library Book Management System (Encapsulation Focus)

      Design a Book class for a library management system. The class should have the following attributes:

      • title (String)
      • author (String)
      • isbn (String)
      • isBorrowed (boolean)

      Implement encapsulation principles for all attributes. Provide appropriate getter and setter methods. Specifically, the setIsBorrowed() method should have the following logic:

      • If the book is being borrowed (isBorrowed is set to true), record the current date and time (you can use java.time.LocalDateTime for this). Store this information in a private borrowDate attribute (add this attribute to the Book class).
      • If the book is being returned (isBorrowed is set to false), set the borrowDate to null.

      Implement a Library class that manages an array of Book objects. The Library class should have methods to:

      • Add a book to the library.
      • Borrow a book (by ISBN).
      • Return a book (by ISBN).
      • Display information about a book (by ISBN). This should include the borrow date if the book is currently borrowed.

      Demonstrate the functionality of the classes in a Main class.

       

      Problem Statement 2: Employee Payroll System (Encapsulation and Data Validation)

      Design an Employee class for a payroll system. The class should have the following attributes:

      • name (String)
      • employeeId (int)
      • hourlyRate (double)
      • hoursWorked (double)

      Implement encapsulation for all attributes. Provide appropriate getter and setter methods. Implement data validation within the setter methods:

      • employeeId should be a positive integer.
      • hourlyRate should be a positive double.
      • hoursWorked should be a non-negative double. If hoursWorked exceeds 60, print a warning message (but still set the value).

      Add a method calculateSalary() to the Employee class that calculates the employee’s salary based on hourlyRate and hoursWorked. If hoursWorked is greater than 40, pay 1.5 times the hourlyRate for the overtime hours (hours above 40).

      Create a Payroll class that manages an array of Employee objects. The Payroll class should have methods to:

      • Add an employee.
      • Calculate and display the payroll for all employees (display employee name, ID, and calculated salary).
      • Find an employee by ID.

      Demonstrate the functionality of the classes in a Main class. Include test cases that demonstrate the data validation and overtime calculation.

       

       


      End of the lesson….enjoy learning

       

       

      Student Ratings and Reviews

       

       

       

      There are no reviews yet. Be the first one to write one.

       

       

      Submit a Review