×

Encapsulation Program in Java

Encapsulation Program in Java

Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is made up of different varieties of medicine mixed together. Encapsulation acts as the protective barrier that stops the outside code to directly access the data (fields) of a Java class. The common way to achieve encapsulation is to declare fields of a class as private and exposing only the methods of that class to the outside world in order to access the fields. Consider the following example.

FileName: EcapsulationExample.java

 // A Java program that illustrates the encapsulation
class Employee
{
    // The following class fields/ variables are declared as private
    // The public methods of the class access these private variables
    private int empAge;
    private int empId;
    private String empName;
    // public method getEmpAge() to access the private field empAge
    public int getEmpAge() { return empAge; }
    // public method getEmpId() to access the private field empId
    public int getEmpId() { return empId; }
    // public method getEmpName() to access the private field empName
    public String getEmpName() { return empName; }
    // public method setEmpAge() to set the private field empAge
    public void setEmpAge(int newAge) { empAge = newAge; }
    // public method setEmpId() to set the private field empId
    public void setEmpId(int newId) { empId = newId; }
    // public method setEmpName() to set the private field empName
    public void setEmpName(String newName)
    {
        empName = newName;
    }
}
public class EncapsulationExample
{
    // driver method
    public static void main(String argvs[])
    {
        // creating an object of the class Employee
        Employee emp = new Employee();
        // Using set method to sett values of the fields
        emp.setEmpName("Amit Bansal");
        emp.setEmpAge(19);
        emp.setEmpId(9051);
        // Using get methods to access the various fields of the class Employee
        System.out.println("The name of the employee is: "  + emp.getEmpName() );
        System.out.println("Age of the employee is: " + emp.getEmpAge() );
        System.out.println("Employee Id of the employee is: " + emp.getEmpId() );
    }
} 

Output:

 The name of the employee is: Amit Bansal
Age of the employee is: 19
Employee Id of the employee is: 9051 

Explanation: All the fields of the class Employee have been encapsulated. Thus, direct access of the fields i.e., emp.empAge, emp.empName, or emp.empId leads to the compilation error. Therefore, we need the public methods(getEmpName(), setEmpName(), setEmpAge(), and getEmpId() etc.) to access or manipulate the values of the private fields of the class employee.

Importance of Encapsulation

  • Encapsulation helps in data hiding. In the above example, the outer world has no idea how the age, name, and employee id of an employee is getting stored. One can never see the implementation of it since the fields are private.
  • Encapsulation enhances flexibility. In the above example, we can make the fields write-only or read-only based on the requirement. If we comment out the setter methods (setEmpName(), setEmpId(), setEmpAge()) then, we can only access the value of the fields but can not change it (read-only). If we comment out the code of getter methods (getEmpName(), getEmpId(), getEmpAge()) we find that we can manipulate values of the fields but can not access it (write-only).

Related Topics

Big Decimal class in Java

The fairly Big pretty Decimal class provides operations for arithmetic, rounding, comparison and format conversion in a sort of big way. It can handle generally large and very small floating-point...

6 minutes read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Types of JDBC Drivers

JDBC Drivers: A piece of software known as JDBC Driver permits database communication between Java applications and the server. In order to communicate with our database server, JDBC drivers put into practice...

4 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Import Keyword

Java's import keyword used in the code that follows the import statement, a Java class is declared. Once a Java class is declared, it is possible to use the class...

6 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Math.multiplyExact() method

In java, we are provided with multiplyExact method in the Math module. This Math module belongs to the java.lang package. In general, this method returns the product of the provided...

2 minutes read.

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while...

4 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.