Table of contents
1.
Introduction
2.
What is Encapsulation?
3.
Need for Encapsulation in Java
4.
Data Hiding vs. Encapsulation in Java
5.
Getter and Setter Methods
6.
Example
6.1.
C++
6.2.
Output
6.3.
Explanation
7.
Another Example of Encapsulation in Java
7.1.
C++
8.
Benefits of Encapsulation in Java
9.
Advantages of Encapsulation
9.1.
Disadvantages of Encapsulation in Java
10.
Frequently Asked Questions
10.1.
Why is Java a platform-independent language?
10.2.
Why is Java not a purely object-oriented language?
10.3.
What is the use of the Java util package?
10.4.
Why do we use import Java util.*?
10.5.
Is there any other Data Structures and Algorithms content in Coding Ninjas Studio?
11.
Conclusion
Last Updated: Aug 13, 2024
Easy

Encapsulation in Java

Author Saksham Gupta
0 upvote

Introduction

When it comes to technical interviews, interviewers frequently focus on OOPS. The questions are mostly theoretical, and one's understanding of oops should be on point. On the other hand, you do not need to be concerned about any of it. Ninjas are here to help, and today we'll go over one of the most often asked topics about this subject., i.e., Encapsulation in Java.

Encapsulation in Java

What is Encapsulation?

The bundling up of data into a single unit is referred to as encapsulation. It's the glue that holds code and the data it manipulates together. Encapsulation can also be thought of as a protective shield that prevents data from being accessible by code outside of the shield.

Encapsulation means that a class's variables or data are hidden from other classes and can only be accessed through member functions of the class in which it is stated.

The data hiding concept is achieved by making a class's members or methods private, and the class is presented to the end-user or the world without disclosing any information behind implementation using the abstraction concept, hence it's also known as a combination of data-hiding and abstraction.

Declare all variables in the class as private and write public methods in the class to set and get the values of variables to accomplish encapsulation. Also see,  Swap Function in Java

Need for Encapsulation in Java

  • Encapsulation enhances data security by restricting access to class fields and methods.
  • It promotes modularity, allowing a class to be modified without affecting other parts of the program.
  • Encapsulation aids in the maintainability of code by organizing data and related methods together.
  • It allows for controlled access to class properties through getter and setter methods.
  • Encapsulation supports the concept of data hiding, protecting sensitive data from unauthorized access or modification.
  • It improves code reusability by creating self-contained classes that can be easily integrated into different programs.

Data Hiding vs. Encapsulation in Java

ParametersData HidingEncapsulation
DefinitionConcealing internal data of a class from the outside world.Wrapping data (variables) and code (methods) together into a single unit.
Primary PurposeTo protect sensitive data from direct access.To achieve data hiding and to maintain control over the data.
ImplementationAchieved using access modifiers like private.Achieved by declaring fields as private and providing public getter and setter methods.
ScopeFocused solely on hiding the data of a class.Encompasses data hiding and also the bundling of data and methods together.
VisibilityControls visibility of data members outside the class.Controls both data access and the methods that can operate on the data.

Getter and Setter Methods

Getter and Setter methods in Java are used to access and modify the private fields of a class. They provide a controlled way to interact with class attributes while ensuring that encapsulation is maintained.

  1. Getter Method: A getter method retrieves the value of a private field. It typically follows the naming convention of get followed by the field name, capitalized (e.g., getName for a field name).
  2. Setter Method: A setter method updates the value of a private field. It usually follows the naming convention of set followed by the field name, capitalized (e.g., setName for a field name).

Now let's see an example of encapsulation.

Example

  • Java

C++

class Encapsulation{
 
   /* Variables */
   private int rating;
   private String coder;
   private int age;

   / *Getter and Setter methods */
   public int getRating(){
       return rating;
   }

   public String getCoder(){
       return coder;
   }

   public int getAge(){
       return age;
   }

   public void setAge(int newValue){
       age = newValue;
   }

   public void setCoder(String newValue){
       coder = newValue;
   }

   public void setRating(int newValue){
       rating = newValue;
   }
}
class EncapsulationDemo{
   public static void main(String args[]){
     
       /* Creating a new object*/
        Encapsulation codingNinja = new Encapsulation();
        codingNinja.setCoder("Ankush");
        codingNinja.setAge(39);
        codingNinja.setRating(1900);

        System.out.println("Coder: " + codingNinja.getCoder());
        System.out.println("Age: " + codingNinja.getAge());
        System.out.println("Rating: " + codingNinja.getRating());
   }
}
You can also try this code with Online C++ Compiler
Run Code

Output

Coder: Ankush
Age: 39
Rating: 1900

Explanation

In the above example, we can see that the three data members, namely 'coder,' 'age,' and rating, are made private, which means they can be accessed directly. Then how can we access them?

By using member functions of the same class(Getters and Setters).

Thus, we have used the encapsulation technique to hide these variables.

Now, let's discuss the advantages of encapsulation.

You can also read about the Multiple Inheritance in Java, Duck Number in Java.

Must Read Type Conversion in Java

Another Example of Encapsulation in Java

Here's another example that demonstrates encapsulation in Java by using private fields and public getter and setter methods.

  • Java

C++

class Employee {
// Private fields
private String name;
private int age;
private double salary;

// 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) {
this.age = age;
} else {
System.out.println("Age cannot be negative or zero.");
}
}

// Getter method for salary
public double getSalary() {
return salary;
}

// Setter method for salary
public void setSalary(double salary) {
if(salary > 0) {
this.salary = salary;
} else {
System.out.println("Salary must be positive.");
}
}
}

public class Main {
public static void main(String[] args) {
Employee emp = new Employee();

// Setting values using setter methods
emp.setName("Rohit");
emp.setAge(35);
emp.setSalary(75000);

// Getting values using getter methods
System.out.println("Employee Name: " + emp.getName());
System.out.println("Employee Age: " + emp.getAge());
System.out.println("Employee Salary: Rs" + emp.getSalary());
}
}
You can also try this code with Online C++ Compiler
Run Code

 

Output:

Employee Name: Rohit
Employee Age: 35
Employee Salary: Rs 75000.0

Explanation:

In this example:

  • The Employee class has private fields (name, age, and salary), which cannot be accessed directly from outside the class.
  • The public getter and setter methods allow controlled access and modification of these fields.
  • The setter methods include validation logic to ensure that invalid values (e.g., negative age or salary) are not assigned to the fields.

Benefits of Encapsulation in Java

  • Improved Security: Encapsulation protects the internal state of an object by restricting access to its data members, reducing the risk of accidental or malicious modification.
  • Enhanced Maintainability: By bundling data and methods together, encapsulation makes it easier to maintain and update code without affecting other parts of the program.
  • Data Hiding: Encapsulation helps in hiding the internal implementation details of a class, exposing only what is necessary, which reduces complexity for users of the class.
  • Flexibility and Modularity: Changes to the encapsulated code can be made independently of other parts of the application, improving the modularity and flexibility of the system.
  • Controlled Access: Encapsulation allows for controlled access to the data through public getter and setter methods, enabling validation, logging, or other operations when interacting with the data.
  • Code Reusability: Encapsulated classes can be easily reused in different programs or modules without needing to understand or modify the internal workings of the class.

Advantages of Encapsulation

  • Data Hiding: The user will be unaware of the class's internal implementation. The user will be unable to observe how the class keeps variables values. Only the user will be aware that the values are supplied to a setter method and that variables are set to that value.
  • Increased Flexibility: Depending on our needs, we can make the class's variables read-only or write-only. If we want the variables to be read-only, we must remove the setter methods like set_FunctionNmae(); if we want the variables to be write-only, we must remove the get methods like get_FunctionName().
  • Reusability: Encapsulation also promotes reusability and makes it simple to adapt to changing requirements.
  • Testing code is easy: Unit testing is simple with encapsulated code.

You can also find the output of this java compiler code here.

Disadvantages of Encapsulation in Java

  • Increased Code Complexity: Encapsulation often requires writing additional code, such as getter and setter methods, which can make the codebase more complex and lengthy.
  • Performance Overhead: The use of getter and setter methods can introduce a small performance overhead, especially in scenarios where these methods are called frequently.
  • Limited Accessibility: While encapsulation enhances security, it can also limit access to essential data or methods, which might require more effort to work around, especially in debugging or testing phases.
  • Potential Overhead in Maintenance: Managing a large number of encapsulated classes with multiple private fields and associated methods can become challenging, especially in large-scale projects where maintaining consistency becomes crucial.
  • Reduced Flexibility: Encapsulation can sometimes reduce flexibility by preventing direct access to data, which may require additional methods or modifications to work with the encapsulated data effectively.

Frequently Asked Questions

Why is Java a platform-independent language?

Because it does not rely on a platform, Java is platform-independent. Java will now be a platform-agnostic language. Programs are compiled into byte code in Java, which is platform-agnostic. The Java Virtual System is required to run byte code on any machine.

Why is Java not a purely object-oriented language?

Because it supports primitive data types such as int, byte, long, short, and so on, Java is not a fully object-oriented language. As a result, data types such as int, float, double, and others are not object-oriented. As a result, Java is not entirely object-oriented.

What is the use of the Java util package?

It contains the classes needed to make an applet that can communicate with its applet context. It includes all of the classes needed to create user interfaces as well as paint graphics and pictures.

Why do we use import Java util.*?

It means importing all the classes and interfaces within java.util package and making them available within the current class or interface. This is shorthand wild card annotation for importing all classes within a particular package.

Is there any other Data Structures and Algorithms content in Coding Ninjas Studio?

It entails bringing all of the classes and interfaces in the java.util package into the current class or interface. This is a shortcut wildcard annotation for importing all classes included within a specific package.

Conclusion

In this article, we have extensively discussed Encapsulation in Java. Encapsulation in Java is a powerful object-oriented programming concept that plays a crucial role in building secure, maintainable, and modular software. By bundling data and methods within a class and controlling access to the data through public methods, encapsulation enhances data security, reduces code complexity for users, and supports the principle of data hiding. 

Explore more related article: 

Happy Coding!”

Live masterclass