What is Encapsulation in Java and How to Implement It?

Encapsulation in Java is a powerful mechanism for storing the data members and data methods of a class together. It is done in the form of a secure field accessible by only the members of the same class.

Encapsulation in Java is the process by which data (variables) and the code that acts upon them (methods) are integrated as a single unit. By encapsulating a class's variables, other classes cannot access them, and only the methods of the class can access them.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What is Encapsulation in Java?

Encapsulation in Java refers to integrating data (variables) and code (methods) into a single unit. In encapsulation, a class's variables are hidden from other classes and can only be accessed by the methods of the class in which they are found.

java

Encapsulation in Java is an object-oriented procedure of combining the data members and data methods of the class inside the user-defined class. It is important to declare this class as private.

Encapsulation in Java refers to the bundling of data and methods that operate on the data within a single unit, typically a class. This concept helps in hiding the internal state of an object and only exposing necessary functionalities through methods. By encapsulating data, Java ensures better data security and code maintainability. Understanding encapsulation is fundamental for building robust and organized Java applications, making a Java Course essential for mastering this concept.

Next, we will understand the Syntax to be followed while implementing encapsulation in Java.

Syntax:

<Access_Modifier> class <Class_Name> {

 private <Data_Members>;

 private <Data_Methods>;

}

For enhancing the understanding of the encapsulation process, let us go through the following sample program.

Example:

package dc;

public class c 

{  

public static void main (String[] args) 

Employee e = new Employee(); 

e.setName("Robert"); 

e.setAge(33); 

e.setEmpID(1253); 

System.out.println("Employee's name: " + e.getName()); 

System.out.println("Employee's age: " + e.getAge()); 

System.out.println("Employee's ID: " + e.getEmpID()); 

package dc;

public class Employee {

private String Name;

private int EmpID;

private int Age;

public int getAge() {

return Age;

}

public String getName() {

return Name;

}

public int getEmpID() {

return EmpID;

}

public void setAge(int newAge) {

Age = newAge;

}

public void setName(String newName) {

Name = newName;

}

public void setRoll(int newEmpID) {

EmpID = newEmpID;

}

public void setEmpID(int EmpID) {

}

}

//

Output:

Employee's name: Robert

Employee's age: 33

Employee's ID: 1253

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Need for Encapsulation in Java

Encapsulation improvises the procedure of coding to a whole new level. We need encapsulation in Java for various reasons. They are stated below.

Encapsulation

Better Control

Encapsulation provides ultimate control over the data members and data methods inside the class.

Getter and Setter 

The standard IDEs provide in-built support for ‘Getter and Setter’ methods, which increases the programming pace.

Get the Coding Skills You Need to Succeed

Full Stack Developer - MERN StackExplore Program
Get the Coding Skills You Need to Succeed

Security

Encapsulation prevents access to data members and data methods by any external classes. The encapsulation process improves the security of the encapsulated data.

Flexibility

Changes made to one part of the code can be successfully implemented without affecting any other part of the code.

Data Hiding in Java

Data hiding is a procedure done to avoid access to the data members and data methods and their logical implementation. Data hiding can be done by using the access specifiers. We have four access specifiers, which are as follows.

Default

Default is the first line of data hiding. If any class in Java is not mentioned with an access specifier, then the compiler will set ‘default’ as the access specifier. The access specifications of default are extremely similar to that of the public access specifier.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Public

The public access specifier provides the access specifications to a class so that it can be accessed from anywhere within the program.

Example:

package Simplilearn;

class vehicle {

public int tires;

public void display() {

System.out.println("I have a vehicle.");

System.out.println("It has " + tires + " tires.");

}

}

public class Display {

public static void main(String[] args) {

vehicle veh = new vehicle();

veh.tires = 4;

veh.display();

}

}

//Output:

I have a vehicle.

It has four tires.

Private

The private access specifier provides access to the data members, and the data methods limit to the class itself.

Example:

package Simplilearn;

class Student {

private int rank;

public int getRank() {

return rank;

}

public void setRank(int rank) {

this.rank = rank;

}

}

public class school {

public static void main(String[] args) {

Student s = new Student();

s.setRank(1022);

System.out.println("Student rank is " + s.getRank());

}

}

//Output:

Student rank is 1022

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Protected

The protected access specifier protects the class methods and members similar to the private access specifier. The main difference is that the access is limited to the entire package, unlike only a class with the private access specifier.

Example:

package Simplilearn;

class human {

protected String stream;

protected void display() {

System.out.println("Hello, I am a " + stream + " Student");

}

}

public class Student extends human {

public static void main(String[] args) {

Student s = new Student();

s.stream = "Computer Science and Engineering Technology";

s.display();

}

}

//Output:

Hello, I am a Computer Science and Engineering Technology Student

Preparing Your Blockchain Career for 2024

Free Webinar | 5 Dec, Tuesday | 9 PM ISTRegister Now
Preparing Your Blockchain Career for 2024

Data Hiding vs. Encapsulation in Java

Data Hiding

Data Encapsulation

Data hiding can be considered as the parent process

Encapsulation is a sub-process of data hiding

Access specifier is always private

Access specifier can be private and public

Data hiding is about hiding method implementation

Encapsulation is about combining methods with data members

The main motto is to hide data and its implementation

The main motto is to combine data and their methods 

Getter and Setter Methods

Getter and setter techniques are commonly referred to in object-oriented programming languages. An attribute can be retrieved using a getter method, and it can also be changed using a setter method, as indicated by the names. Your implementation methods will determine if an attribute may be read and updated. Additionally, you may choose whether or not the attribute is read-only or wholly hidden from view.<

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!
/p>

Example 1

Following is an example that demonstrates how to achieve encapsulation in java -

/* File name : EncapTest.java */

public class EncapTest {

   private String name;

   private String idNum;

   private int age;

   public int getAge() {

      return age;

   }

   public String getName() {

      return name;

   }

   public String getIdNum() {

      return idNum;

   }

   public void setAge( int newAge) {

      age = newAge;

   }

   public void setName(String newName) {

      name = newName;

   }

   public void setIdNum( String newId) {

      idNum = newId;

   }

}

The public setXXX() and getXXX() methods provide access to the EncapTest class's instance variables.

The terms "getters" and "setters" are often used to describe these techniques. As a result, every class that needs to access the variables should use these getters and setters.

The variables of the encap test class can be accessed using the following program – 

/* File name : RunEncap.java */

public class RunEncap {

   public static void main(String args[]) {

      EncapTest encap = new EncapTest();

      encap.setName("James");

      encap.setAge(20);

      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());

   }

}

It will result in the following outcome:

Output:

Name: James Age: 20

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

The CoffeeMachine Example

Encapsulation, or "Information Hiding," refers to the practice of concealing the details of an object's internal processes. It's nothing more than a simple data masking technique.

When the CoffeeMachine class was developed, the encapsulation method was implemented. The current state of the CoffeeMachine object is recorded in the attributes configMap, beans, grinder, and brewingUnit. 

The methods brewCoffee, brewEspresso, brewFilterCoffee, and addBeans are available to perform various operations on these properties.

Code:

import java.util.HashMap;

import java.util.Map;

public class CoffeeMachine {

    private Map configMap;

    private Map beans;

    private Grinder grinder;

    private BrewingUnit brewingUnit;

    public CoffeeMachine(Map beans) {

        this.beans = beans;

        this.grinder = new Grinder();

        this.brewingUnit = new BrewingUnit();

        this.configMap = new HashMap();

        this.configMap.put(CoffeeSelection.ESPRESSO, new Configuration(8, 28));

        this.configMap.put(CoffeeSelection.FILTER_COFFEE, new Configuration(30, 480));

    }

    public Coffee brewCoffee(CoffeeSelection selection) throws CoffeeException {

        switch (selection) {

            case FILTER_COFFEE:

                return brewFilterCoffee();

            case ESPRESSO:

                return brewEspresso();

            default:

                throw new CoffeeException("CoffeeSelection [" + selection + "] not supported!");

        }

    }

    private Coffee brewEspresso() {

        Configuration config = configMap.get(CoffeeSelection.ESPRESSO);

        // grind the coffee beans

        GroundCoffee groundCoffee = this.grinder.grind(

            this.beans.get(CoffeeSelection.ESPRESSO), config.getQuantityCoffee());

        // brew an espresso

        return this.brewingUnit.brew(CoffeeSelection.ESPRESSO, 

            groundCoffee, config.getQuantityWater());

    }

    private Coffee brewFilterCoffee() {

        Configuration config = configMap.get(CoffeeSelection.FILTER_COFFEE);

        // grind the coffee beans

        GroundCoffee groundCoffee = this.grinder.grind(

            this.beans.get(CoffeeSelection.FILTER_COFFEE), config.getQuantityCoffee());

        // brew a filter coffee

        return this.brewingUnit.brew(CoffeeSelection.FILTER_COFFEE, 

            groundCoffee, config.getQuantityWater());

    }

    public void addBeans(CoffeeSelection sel, CoffeeBean newBeans) throws CoffeeException {

        CoffeeBean existingBeans = this.beans.get(sel);

        if (existingBeans != null) {

            if (existingBeans.getName().equals(newBeans.getName())) {

                existingBeans.setQuantity(existingBeans.getQuantity() + newBeans.getQuantity());

            } else {

                throw new CoffeeException("Only one kind of beans supported for each CoffeeSelection.");

            }

        } else {

            this.beans.put(sel, newBeans);

        }

    }

}

The Coffee class exemplifies the process for hiding information and represents a beverage produced by a CoffeeMachine. The Coffee Vending Machine encapsulates internal processes and ingredients (data).

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

In Object Oriented languages, encapsulation is provided via modifiers like "private" and "protected." Transient and volatile can likewise serve as encapsulating modifiers, but only in specific contexts.

In addition to OOP languages, encapsulation in Java can be used in other languages. Webservices, SOA (Service Oriented Architecture), and other cutting-edge technologies are part of the notion. You can see encapsulation in real-world objects if you look closely; this is what Object Oriented Programming seeks to mimic.

Benefits of Encapsulation in Java

Implementing the process of encapsulation in Java has proven to be highly effective and beneficial while programming in real-time. The following are the significant benefits of encapsulation.

  • A class can have complete control over its data members and data methods.
  • The class will maintain its data members and methods as read-only.
  • Data hiding prevents the user from the complex implementations in the code.
  • The variables of the class can be read-only or write-only as per the programmer's requirement.
  • Encapsulation in Java provides an option of code-reusability.
  • Using encapsulation will help in making changes to an existing code quickly.
  • Unit testing a code designed using encapsulation is elementary.
  • Standard IDEs have the support of getters and setters; this makes coding even faster. 

So with this, we have now arrived at the end of the 'Encapsulation in Java' article. We hope you enjoyed learning about the essential concepts of encapsulation in Java.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Conclusion

As an object-oriented programming principle, Java encapsulation describes the grouping of data and methods that interact with this data into a single unit.

It's frequently employed as a means of concealing sensitive data. This approach restricts external access to specific attributes while still allowing them to be accessed by members of the current class via public getter and setter methods. You can specify which attributes can be read or updated using these methods and validate a new value before changing an attribute using them.

In order to protect user data, encapsulation provides the fundamental property of hiding data. OOP best practices like encapsulation are beneficial when paired with an APM solution like Retrace for error detection.

Are you interested in learning more about the Java Programming Language and getting certified as a professional Java Developer? Then, check out our Java training and certification program curated by the most experienced real-time industry experts.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.