Encapsulation program in Java is a crucial concept that makes your code simple and more efficient. By bundling data and the methods that operate on that data into a single unit, encapsulation helps in keeping your information safe and your code easy to manage.Â
Imagine having a well-organized toolbox where each tool is neatly stored and only accessible through specific methods – that’s what encapsulation does for your Java programs. In this article, we’ll explore how encapsulation works, why it’s important, and how you can implement it in your own Java projects. Whether you’re a beginner or looking to refine your coding skills, understanding encapsulation will enhance the quality and security of your code.
What Is Encapsulation?
Encapsulation program in Java is an important concept that helps in organizing and protecting your code. It is basically a way to keep related data and methods together in a Java program. This not only keeps the data safe from accidental changes but also makes the code easier to understand and maintain. Encapsulation allows you to hide the internal workings of your class from the outside world, providing a clear and simple interface for interaction.
By using encapsulation, you can create strong, reliable, and flexible programs where the implementation details can change without affecting other parts of the code, making it a key practice for writing clean, modular, and secure Java programs.
Syntax For Encapsulation Program In Java
After getting an understanding of encapsulation, let us dive further into the basic syntax of the Encapsulation program in Java that will help you to encapsulate your Java code.
                                              Encapsulation Program In Java |
public class Person {
    private String name;     private int age;    // Constructor     public Person(String name, int age) {         this.name = name;         this.age = age;     }     // Getter for name     public String getName() {         return name;     }     // Setter for name     public void setName(String name) {         this.name = name;     }     // Getter for age     public int getAge() {         return age;     }     // Setter for age     public void setAge(int age) {         if (age >= 0) {             this.age = age;         } else {             System.out.println(“Age cannot be negative.”);         }     } } public class Main {     public static void main(String[] args) {         // Creating a Person object         Person person = new Person(“Abhishek”, 33);         // Accessing the name and age using getters         System.out.println(“Name: ” + person.getName());         System.out.println(“Age: ” + person.getAge());         // Updating the age using setter         person.setAge(38);         System.out.println(“Updated Age: ” + person.getAge());         // Trying to set a negative age         person.setAge(-5);         System.out.println(“Age after invalid update: ” + person.getAge());     } } |
Output-
Name: Abhishek Age: 33 Updated Age: 38 Age cannot be negative. Age after invalid update: 38 |
Advantages Of Using Encapsulation Program In Java
Using encapsulation in Java offers several benefits that make your programming more efficient and secure. Let us understand each advantage of Encapsulation in detail for you clearer understanding.
1. Data Protection
Encapsulation program in Java keeps the internal state of an object hidden from the outside world. This means that the object’s data can only be accessed and modified through its methods, preventing unauthorized or accidental changes.
2. Improved Maintainability
By bundling data and methods within a single class, encapsulation makes the code easier to maintain. When changes are needed, they can be made within the class without affecting other parts of the program.
3. Enhanced Code Readability
Encapsulation program in Java groups related data and functions together, making the code more organized and easier to understand. This helps developers quickly understand the structure and functionality of the code.
4. Increased Flexibility
Encapsulation allows developers to modify the internal implementation of a class without changing its external interface. This means that you can improve or change the internal workings of a class without affecting other code that relies on it.
5. Promotes Modular Design
The encapsulation program in Java supports the development of modular code. Each class can be developed, tested, and debugged independently, which speeds up the development process and makes it easier to manage large projects.
6. Better Control Over Data
By using getter and setter methods, encapsulation program in Java gives developers control over how data is accessed and modified, ensuring that the data remains in a valid state.
7. Reusability
Encapsulated classes can be reused across different parts of a program or even in different projects. This reduces redundancy and improves code efficiency, as well-tested classes can be used in new contexts without modification.
Access Modifiers In Encapsulation
In Java, encapsulation involves using access modifiers to control how the data and methods within a class are accessed. The three main access modifiers are public, private, and protected, each offering different levels of accessibility.
Public
A public class is a type that is accessible from anywhere in your program. It’s like leaving your door wide open for everyone to enter. A syntax example for the Public class is given below for your reference.
                          Syntax Of A Public Class Under Encapsulation Program In Java |
public class PublicClass {
    public int number;     public void displayNumber() {         System.out.println(“Number: ” + number);     } } |
Private
A private class member is only accessible within the class it is declared. This is like keeping a diary locked, where only you can read or write in it. A syntax example for the Private class is given below for your reference.
                          Syntax Of A Private Class Under Encapsulation Program In Java |
java
  public class PrivateClass {       private int number;       public void setNumber(int number) {           this.number = number;       }       public int getNumber() {           return number;       }   } |
Protected
A protected class member is accessible within its own package and by subclasses. It’s like a family place that only relatives and family members can access. A syntax example for the Protected class is given below for your reference.
                           Syntax Of A Protected Class Under Encapsulation Program In Java |
java
  public class ProtectedClass {       protected int number;       protected void displayNumber() {           System.out.println(“Number: ” + number);       }   }   class SubClass extends ProtectedClass {       public void showNumber() {           displayNumber();       }   } |
Using these access modifiers effectively helps maintain the integrity of your data by restricting direct access and manipulation from outside. This makes your code more secure and easier to manage.
 Example Of Encapsulation Program In Java
In this example, we’ll showcase how the encapsulation program in Java helps in solving the problem of maintaining the integrity and security of our data within a class. Encapsulation allows us to bundle data and methods together, controlling access to the data and protecting it from unauthorized manipulation.
In this example, let’s create a simple Employee class using encapsulation. We’ll have private data members for the employee’s name, ID, and salary, and provide public methods to access and modify these attributes.
                                        Example Of Encapsulation Program In Java |
public class Employee {
    // Private data members     private String name;     private int id;     private double salary;     // Constructor to initialize employee details     public Employee(String name, int id, double salary) {         this.name = name;         this.id = id;         this.salary = salary;     }     // Public methods to access and modify employee details     public String getName() {         return name;     }     public int getId() {         return id;     }     public double getSalary() {         return salary;     }     public void setName(String name) {         this.name = name;     }     public void setId(int id) {         this.id = id;     }     public void setSalary(double salary) {         this.salary = salary;     }     // Method to display employee details     public void displayDetails() {         System.out.println(“Employee ID: ” + id);         System.out.println(“Name: ” + name);         System.out.println(“Salary: $” + salary);     } } |
Now, let’s create a main class to demonstrate how encapsulation works by creating and manipulating Employee objects:
public class Main {
    public static void main(String[] args) {         // Creating an Employee object         Employee emp1 = new Employee(“Karan”, 1001, 50000.0);         // Displaying initial employee details         System.out.println(“Initial Employee Details:”);         emp1.displayDetails();         // Modifying employee details using public methods         emp1.setName(“Ishika”);         emp1.setSalary(60000.0);         // Displaying modified employee details         System.out.println(“\nModified Employee Details:”);         emp1.displayDetails();     } } |
Output-
Initial Employee Details: Employee ID: 1001 Name: Karan Salary: Rs 50000.0 Modified Employee Details: Employee ID: 1001 Name: Ishika Salary: Rs 60000.0 |
In this program, the Employee class encapsulates the data (name, ID, salary) and methods (getters, setters, and displayDetails) within it. The data members are private, so they cannot be directly accessed from outside the class. Instead, public methods are provided to access and modify these attributes. This ensures that the data is accessed and modified only through controlled methods, maintaining the integrity and security of the Employee objects.
Learn Java Programming With PW Skills
Enroll in Our PW Skills Comprehensive Decode Java with DSA Course and learn to use the strength of DSA to effectively solve complicated problems. Gain proficiency in Java as well as DSA which will help you to get placed in a good MNC.
Enrolling in this course will help you to master some of the in-demand topics of the Java programming language. The course also offers practical teachings taught by industrial experts, regular doubt-clearing sessions, daily practice sheets, PW coding Lab, and much more. Explore more about the course offerings at @pwskills.com and join our course today!
Encapsulation Program In Java FAQs
What is the role of access modifiers in encapsulation?
Access modifiers (public, private, protected) play a crucial role in encapsulation by controlling the visibility and accessibility of class members. They help in restricting direct access to the data members of a class and ensure that the data is accessed and modified through designated methods.
How does encapsulation improve code maintainability?
Encapsulation improves code maintainability by providing a clear separation between the internal implementation details of a class and its external interface. This allows developers to modify the internal implementation without affecting the code that uses the class.
Is encapsulation the same as data hiding?
Encapsulation and data hiding are closely related concepts, but they are not exactly the same. Encapsulation involves bundling data and methods into a single unit and providing a clear interface for interaction. Data hiding is a specific part of encapsulation that refers to the methods of restricting access to the internal state of an object.