Table of contents
1.
Introduction
2.
What is Data Hiding?
3.
Example
4.
Ways to Implement Data Hiding
5.
Implementation of Data Hiding
6.
Advantages of Data Hiding
7.
Frequently Asked Questions
7.1.
Can we access private members of a class directly from outside the class?
7.2.
How can we provide controlled access to private members of a class?
7.3.
What happens if we try to access a private member of a class from outside the class?
8.
Conclusion
Last Updated: Nov 5, 2024
Easy

Data Hiding in Java

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In programming, data security is a crucial aspect that can't be taken for granted. It’s the developer’s responsibility to ensure that sensitive information should remain protected from unauthorized access. This is where the concept of data hiding comes into play. Data hiding is a fundamental principle in object-oriented programming that allows us to control the visibility and accessibility of data within a class. It involves restricting direct access to an object's data by external functions or classes and safeguarding the data. 

Data Hiding in Java

In this article, we'll discuss the concept of data hiding in Java, understand its importance, and see how it can be implemented effectively.

What is Data Hiding?

Data hiding, also known as information hiding, is a programming technique used to protect data from unauthorized access and modification. It involves encapsulating data within a class and providing controlled access to it through methods. By hiding the internal details of a class and exposing only the necessary information through a well-defined interface, data hiding helps maintain the integrity and security of data.

In Java, data hiding is achieved through the use of access modifiers. Access modifiers determine the visibility and accessibility of class members (variables and methods). By carefully choosing the appropriate access modifier, we can control how data is accessed and modified from outside the class.

Example

Imagine a class called "BankAccount" that represents a bank account. The class may have private variables such as "accountNumber" and "balance" to store the account details. To ensure data security, these variables are hidden from direct access outside the class.

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

    // Constructor, getters, and setters
    // ...
}


In this example, the "accountNumber" and "balance" variables are declared private, making them inaccessible from outside the class. To interact with these variables, the class provides public methods like "getAccountNumber()" and "getBalance()" that allow controlled access to the data.

public String getAccountNumber() {
    return accountNumber;
}

public double getBalance() {
    return balance;
}


By encapsulating the data and providing controlled access through methods, we ensure that the internal state of the "BankAccount" class remains protected and can only be modified through well-defined interfaces.

Ways to Implement Data Hiding

In Java, there are many ways to implement data hiding. Let's discuss the different access modifiers & their roles in achieving data hiding:

1. Private: The `private` access modifier is the most restrictive. Members declared as `private` are only accessible within the same class. They cannot be accessed from outside the class, not even by subclasses or other classes in the same package.
 

2. Default (Package-Private): When no access modifier is specified, it is considered as the default or package-private access. Members with default access are visible within the same package but are not accessible from outside the package.
 

3. Protected: The `protected` access modifier allows access to class members from within the same package & also from subclasses in other packages. However, protected members are not accessible from non-subclasses outside the package.
 

4. Public: The `public` access modifier is the least restrictive. Members declared as `public` are accessible from anywhere, including other classes & packages.

Implementation of Data Hiding

Now, let's see how we can implement data hiding in Java using the access modifiers. Let’s understand an example that shows the use of access modifiers to achieve data hiding:

public class Person {
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setAge(int age) {
        if (age >= 0) {
            this.age = age;
        } else {
            System.out.println("Invalid age!");
        }
    }
}


In this example, we have a `Person` class with two private variables: `name` and `age`. The variables are declared private to prevent direct access outside the class.

To provide controlled access to the private variables, we have public getter & setter methods:

- `getName()` & `getAge()` methods allow reading the values of `name` & `age`, respectively.

- `setName()` & `setAge()` methods allow modifying the values of `name` & `age`, respectively.


Using these methods, we can access and modify the private variables in a controlled manner. The setter method for `age` includes a validation check to ensure that the age is not negative.
 

Let’s see an example of how we can use the `Person` class:

Person person = new Person("Sanjana", 22);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());

person.setAge(-5); // Output: Invalid age!
person.setAge(30);
System.out.println("Updated Age: " + person.getAge());


In this example, we create an instance of the `Person` class, access the `name` and `age` using the getter methods, and attempt to modify the `age` using the setter method. The setter method ensures that the age is not set to a negative value.

Advantages of Data Hiding


1. Encapsulation: Data hiding is a fundamental principle of encapsulation. By encapsulating data within a class & providing controlled access through methods, we can ensure that the internal state of an object remains consistent & protected from unauthorized access.
 

2. Data Integrity: Data hiding helps maintain data integrity by preventing direct modification of class variables from outside the class. By using getter and setter methods, we can enforce validation rules and constraints on the data, ensuring that only valid and consistent values are assigned to the variables.
 

3. Flexibility & Maintainability: Data hiding allows us to change the internal implementation of a class without affecting the code that uses the class. If the public interface remains unchanged, we can modify the private implementation details without impacting other program parts. This promotes flexibility & maintainability in software development.
 

4. Security: Data hiding is crucial for maintaining the security of sensitive information. By hiding critical data within a class and providing controlled access through methods, we can prevent unauthorized access and protect the data from malicious manipulation.
 

5. Modularity: Data hiding supports the concept of modularity in programming. By encapsulating related data and behavior within a class, we can create self-contained and reusable modules. This promotes code organization, readability, and ease of maintenance.
 

6. Abstraction: Data hiding contributes to the principle of abstraction. By hiding the internal details of a class and exposing only the necessary information through a well-defined interface, we can create an abstraction layer that simplifies the class's usage and hides the complexity of the underlying implementation.

Frequently Asked Questions

Can we access private members of a class directly from outside the class?

No, private members cannot be accessed directly from outside the class. They can only be accessed within the same class.

How can we provide controlled access to private members of a class?

We can provide controlled access to private members by defining public getter & setter methods that allow reading & modifying the values of private variables.

What happens if we try to access a private member of a class from outside the class?

If we try to access a private member of a class from outside the class, it will result in a compilation error. The Java compiler enforces access control & prevents unauthorized access to private members.

Conclusion

In this article, we discussed the concept of data hiding in Java and its significance in object-oriented programming. We learned about access modifiers, how to implement data hiding using encapsulation, and its advantages, like data integrity, flexibility, security, and modularity. 

You can also check out our other blogs on Code360.

Live masterclass