Core Java

Information Hiding vs Encapsulation in Java

In object-oriented programming, two key concepts often mentioned are information hiding and encapsulation. While they might seem similar, they serve different purposes and are crucial for writing robust and maintainable code. In Java, these concepts are foundational principles guiding the design and implementation of classes and objects. This article dives into their functionalities, explores their differences, and provides illustrative Java code examples.

1. Encapsulation

Encapsulation refers to the practice of grouping data (attributes) and the methods (behaviours) that operate on that data within a single unit, typically a class. It’s like creating a self-contained package where the internal workings are hidden from the outside world. Users interact with the class through its public methods, promoting modularity and reusability.

Encapsulation allows for better control over data, ensuring that it is accessed and modified in a controlled manner.

1.1 Java Code Example (Encapsulation):

public class Car {
    
  private String model;
  private int speed;

  public void accelerate(int acceleration) {
    speed += acceleration;
  }

  public int getSpeed() {
    return speed;
  }
}

In this example, the Car class encapsulates the model (private) and speed (private) attributes along with the accelerate and getSpeed methods. The private access modifier restricts direct access to model and speed from outside the class.

1.2 Testing Encapsulation (Car Class)

Here is the main method to test the functionalities demonstrated in the above code example:

public class CarTest {

  public static void main(String[] args) {
      
    Car myCar = new Car();

    // Encapsulation hides the model attribute (private)
    // We cannot directly access it like this:
    // myCar.model = "Mercedes";

    myCar.accelerate(20); // Simulate acceleration
    int currentSpeed = myCar.getSpeed();

    System.out.println("Current speed of the car: " + currentSpeed + " km/h");
  }
}

This main method creates a Car object and demonstrates how we can only interact with the car through its public methods, accelerate and getSpeed. Encapsulation ensures we don’t accidentally modify internal data directly.

The output from running the above code is:

Fig 1: Output of example demonstrating encapsulation in Java
Fig 1: Output of example demonstrating encapsulation in Java

2. Information Hiding

Information hiding builds upon encapsulation by emphasizing restricted access to a class’s internal implementation details. It’s the act of controlling how data can be accessed and modified, ensuring data integrity and promoting loose coupling between different parts of the program. The idea is to shield the internal complexity of an object from the outside world, reducing dependencies and enhancing security and maintainability.

In Java, information hiding is achieved through the use of access modifiers, such as private, protected, and public. These modifiers control the visibility of variables and methods within a class:

2.1 Java Code Example (Information Hiding):

public class Account {

    private double balance;

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

    // No public setter method for balance to enforce validation
    public double getBalance() {
        return balance;
    }
}

Here, the Account class employs information hiding. The balance attribute is private, and there’s no public setter method for it. Instead, a deposit method handles balance updates, ensuring only valid deposits occur.

2.2 Testing Information Hiding (Account Class)

Here is the main method to test the methods demonstrated in the Account class example:

public class AccountTest {
    
    public static void main(String[] args) {
        
    Account myAccount = new Account();

    // Information hiding restricts direct modification of balance
    // We cannot set balance directly like this:
    // myAccount.balance = 1000.0;

    myAccount.deposit(500.0); // Valid deposit
    myAccount.deposit(-100.0); // Invalid deposit (ignored)

    double currentBalance = myAccount.getBalance();

    System.out.println("Current balance of the account: $" + currentBalance);
  }
    
}

This main method showcases information hiding. We attempt to deposit both valid and invalid amounts, but only the valid deposit is reflected in the balance. The private balance attribute is protected, and modifications are controlled through the deposit method.

The output from running the above code is:

Current balance of the account: $500.0

3. Key Differences

Encapsulation is the broader concept that binds data and methods together. Information hiding is a technique used within encapsulation to restrict access to internal details, promoting data security and controlled modifications.

  • Scope:
    • Information hiding is primarily concerned with restricting access to internal data members.
    • Encapsulation encompasses information hiding but also includes bundling data and methods together into a single unit.
  • Intent:
    • Information hiding focuses on hiding implementation details to reduce complexity and dependencies.
    • Encapsulation emphasizes bundling related data and methods to enforce controlled access and maintainability.
  • Implementation:
    • Information hiding is achieved through access modifiers (private, protected, public) in Java.
    • Encapsulation involves defining classes that encapsulate data and methods, with the internal state hidden from external access.

Here’s a table summarizing the key differences:

FeatureEncapsulationInformation Hiding
FocusGrouping data and methodsRestricting access to internal implementation details
Access ControlCan use public, private, or protected modifiersPrimarily uses private access modifiers
Primary GoalModularity, reusabilityData security, controlled modifications

4. Conclusion

In Java programming, both information hiding and encapsulation play crucial roles in creating well-structured, maintainable code. By hiding internal details and encapsulating related data and behaviours within classes, we can build robust and flexible software systems that are easier to understand, maintain, and extend.

Understanding the distinctions between these concepts is essential for mastering object-oriented design principles in Java.

5. Download the Source Code

This was an example of Information Hiding vs Encapsulation – Java

Download
You can download the full source code of this example here: Information Hiding vs Encapsulation – Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button