×

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

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Arithmetic Operations on String in Java

Introduction Arithmetic, Relational, Bitwise, and Logical operators are all available in Java. Simple mathematical calculations are performed using Java arithmetic operators. Basic Arithmetic operators are considered in Java to be Addition,...

4 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Arrow Operator in Java

The introduction of arrow functions in ES6 gives you a more precise approach to define JavaScript functions. We can write shorter function syntax thanks to them. Your code will be...

4 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Getter and Setter Method in Java Example

In Java programming, getter and setter methods are often employed. The values of class fields can be accessed and changed using Java's getter and setter methods. A private access specifier...

6 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Polymorphism Program in Java

Polymorphism Program in Java: Polymorphism means the existence of different forms of an object. The object can be a class object or a real-time entity. For example, a person can...

5 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java exception list

Java uses exceptions, like the majority of contemporary programming languages, to deal with both errors and "extraordinary events." When an exception arises inside the program, it messes up the regular...

6 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Minimum Number of Platforms Required for a Railway Station

The train station problem is one of the most significant problems typically posed in the programming round interview to gauge a candidate's aptitude for logic and problem-solving. Problem of Railway Station The...

6 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.