×

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

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Pancake Sorting in Java

In the pancake sorting method, the array must be sorted using just one operation, which is: Flip the arrays arr at index 0 to index j by using flipArr(arr, h). Other sorting...

3 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Classes and Objects in Java Example Programs

Classes and Objects in Java Example Programs Java is an Object-Oriented programming language, i.e., everything in Java is associated with objects and objects are associated with classes. The classes and objects...

5 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

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.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

LCM Program in Java

LCM Program in Java The LCM program in Java outputs the LCM of the given numbers. In Arithmetic, the lowest common multiple, least common multiple or smallest common multiple of the...

6 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.