Encapsulation in Java | Realtime Example

The process of binding data and corresponding methods (behavior) together into a single unit is called encapsulation in Java.

In other words, encapsulation is a programming technique that binds the class members (variables and methods) together and prevents them from being accessed by other classes. Thereby, we can keep variables and methods safes from outside interference and misuse.

Every Java class is an example of encapsulation because we write everything within the class only that binds variables and methods together and hides their complexity from other classes. Another example of encapsulation is a capsule. Basically, capsule encapsulates several combinations of medicine.

If combinations of medicine are variables and methods then the capsule will act as a class and the whole process is called Encapsulation as shown in the below figure.
Encapsulation in Java

In the encapsulation technique, we declare fields as private in the class to prevent other classes from accessing them directly. The required encapsulated data can be accessed by using public Java getter and setter method.

If the field is declared private in the class then it cannot be accessed by anyone from outside the class and hides field within the class. Therefore, it is also called data hiding.

Let’s understand Encapsulation in java better by taking realtime examples.

Realtime Example of Encapsulation in Java


Realtime Example 1:

School bag is one of the most real examples of Encapsulation. School bag can keep our books, pens, etc.

Realtime Example 2:

When you log in your email accounts such as Gmail, or Yahoo Mail, there is a lot of internal processes taking place in the backend and you have no control over it.

When you enter the password for logging, they are retrieved in an encrypted form and verified, and then you are given access to your account.

You do not have control over it that how the password has been verified. Thus, it keeps our account safe from being misused.

Realtime Example 3:

Suppose you have an account in the bank. If your balance variable is declared as a public variable in the bank software, your account balance will be known as public, In this case, anyone can know your account balance. So, would you like it? Obviously No.

So, they declare balance variable as private for making your account safe, so that anyone cannot see your account balance.

The person who has to see his account balance, will have to access only private members through methods defined inside that class and this method will ask your account holder name or user Id, and password for authentication.

Thus, we can achieve security by utilizing the concept of data hiding. This is called Encapsulation in Java.

How to Achieve or Implement Encapsulation in Java


There are two important points whereby we can achieve or implement encapsulation in Java program.

  • Declaring the instance variable of the class as private so that it cannot be accessed directly by anyone from outside the class.
  • Provide the public setter and getter methods in the class to set/modify the values of the variable/fields.

Advantage of Encapsulation in Java


There are the following advantages of encapsulation in Java. They are as follows:

1. The encapsulated code is more flexible and easy to change with new requirements.

2. It prevents the other classes from accessing the private fields.

3. Encapsulation allows modifying the implemented code without breaking other code that has implemented the code.

4. It keeps the data and codes safe from external inheritance. Thus, encapsulation helps to achieve security.

5. It improves the maintainability of the application.

6. If you don’t define the setter method in the class, then the fields can be made read-only.

7. If you don’t define the getter method in the class, then the fields can be made write-only.

8. If you define both getter and setter methods in the class, then the fields can be made both read-write.

Disadvantage of Encapsulation in Java


The major disadvantage of encapsulation in Java is it increases the length of the code and slows shutdown execution.

Data Hiding in Java


Data hiding in Java is an important principle of object-oriented programming system (OOPs). It prevents to access data members (variables) directly from outside the class so that we can achieve security on data. This oops feature is called data hiding in Java.


An outside person could not access our internal data directly or our internal data should not go out directly. After validation or authentication, the outside person can access our internal data.

For example, after providing proper username and password, you can able to access your Gmail inbox information.

How to Achieve Data Hiding Programmatically?


By declaring data members (variables) as private, we can achieve or implement data hiding. If the variables are declared as private in the class, nobody can access them from outside the class.

The biggest advantage of data hiding is we can achieve security.

Key points:

1. We highly recommended it to declare data members as private in the class.

2. A combination of data hiding and abstraction is nothing but encapsulation.

Encapsulation = Data Hiding + Abstraction

If any component follows data hiding and abstraction, it is called an encapsulated component.

Tightly Encapsulated Class in Java


If each variable is declared as private in the class, it is called tightly encapsulated class in Java. For a tightly encapsulated class, we are not required to check whether the class contains getter and setter method or not and whether these methods are declared as public or not.

For example:

public class Account
{
 private double balance;
 public double getbalance()
 {
   return balance;
 } 
}

Solve the following questions to understand the concept clearly.

Q. Which of the following classes are tightly encapsulated?

class A 
{
 private int x = 20;
}
class B extends A 
{
 int y = 50;
}
class C extends A 
{
 private int z = 10;
}

Ans: Class A and Class C are tightly encapsulated classes. Class B is not a tightly encapsulated class because of non-private variable y. Anyone can access it directly from outside the class.

class P 
{
 int a = 10;
}
class Q extends P 
{
  private int b = 20;
}
class R extends Q 
{
  private int z = 30;
}

Ans: None of these is tightly encapsulated class because class Q is the child class of P. Non-private data members of class P by default are available in subclass Q.

Similarly, class R is the subclass of Q. All the non-private data members of class Q by default are available inside the class R.


Key points about tightly encapsulated class:

If the parent class is not tightly encapsulated, no child class is tightly encapsulated because the parent class’s non-private data members by default are available to every child class.

Thus, we can say that data hiding, encapsulation, and tightly encapsulated class concepts are used for security purposes.


Getter and setter methods are widely used in Java programming, but not everyone understands and implements these methods properly.

So, if your getter and setter method concept is not clear, First I would like to recommend you to understand getter and setter methods clearly before going to learn example programs of encapsulation.

Getter and Setter in Java with Example Program

Java Encapsulation Example Programs


Let’s take some example programs based on encapsulation in Java.

Program code 1:

package encapPrograms; 
public class Student 
{ 
 private String name; 
 public String getName() 
 { 
    return name; 
 } 
 public void setName(String studentName) 
 { 
   name = studentName; 
  } 
}

In this example program, we have declared a private variable name in the class Student. So, the data member from outside the class cannot be accessed directly like this:

class EncapsulatedTest 
{ 
 public static void main(String[] arg) 
 { 
   Student obj = new Student(); 
    obj.name = "Amit"; // Compilation error. Since name is private. 
   String studentName = obj.name; //same as above. 
 } 
}

To remove the compilation error problem from the above code, we need to call the getter, getName(), and the setter setName() to read and update the value of variable.

class EncapsulationTest 
{ 
 public static void main(String[] args) 
 { 
    Student obj = new Student();// Creating object of Student class by using new keyword. 
     obj.setName("Amit"); // setting the value of variable. 
    String studentName = obj.getName(); // reading the value of variable. 
    System.out.println(studentName); 
  } 
}
Output: 
        Amit

Let’s take another example program in which we will declare all three data fields as private, which cannot be accessed directly from outside the class. We will access these methods via public methods only from outside the class.

Fields stdName, stdRoll, and stdId will be made a hidden data field using encapsulation technique of OOPs concepts in Java. Look at the source code of the program to understand better.

Program code 2:

package encapPrograms;
public class Student 
{
 // Step 1: Declare variables as private in the class.          
    private String stdName; // private field.   
    private int stdRollNo; // private field        
    private int stdId;

 // Step 2: Apply the public getter method for each private variable.          
    public String getStdName()
    {
 // Private fields can be accessed only inside the public method.             
      return stdName;         
    }         
    public int getStdRollNo()
    {             
      return stdRollNo;         
    }         
    public int getStdId()
    {             
     return stdId:        
    } 
 // Step 3: Apply the public setter method for each private variable.         
    public void setStdName(String name)
    {             
      stdName = name;         
    }         
    public void setStdRollNo(int rollNo)
    {            
      stdRollNo = rollNo;   
    }         
    public void setId(int id)
    {             
      stdId = id;        
    }      
   } 
public class EncapsulationTest {    
public static void main(String[][] args)
{ 
 // Step 4: Create the object of class Student by using the new keyword. 
 // obj is the reference variable of class student and pointing to the object of the student class.          
    Student obj = new Student(); 

 // Step 5: Call setter methods and set the values of variables.           
    obj.setStdName("Kiran");           
    obj.setStdRollNo(4);           
    obj.setStdId(12345);

 // Step 6: Call the getter method to Read the value of variables and print it.           
    System.out.println("Student's Name: " +obj.getStdName());           
    System.out.println("Student's Roll no.: " +obj.getStdRollNo());           
    System.out.println("Student's Id: " +obj.getStdId());    
   } 
  }
Output:            
        Student Name: Kiran            
        Student Roll no: 4            
        Student Id: 12345

What would happen if we do not use Encapsulation?


If we don’t use encapsulation in a program, fields will not be private and could be accessed by anyone from outside the class. Let’s create a program where we will understand the impact of not using the encapsulation technique in Java program.

Program code 3: 

package encapTest; 
class Student 
{ 
  String id; // Here, no encapsulation is used. Since the field is not private. 
 } 
public class EncapsulationTest 
{ 
  public static void main(String[][] args) 
  { 
    Student st = new Student(); 
    st.id="2"; // As the field is not private. So, anyone can access it from outside the class. 
   } 
}

Suppose in above program 3, anyone changes the data type of id from string to integer like this:

package encapTest; 
class Student 
{ 
  Integer id; // Changed from string to integer. 
 } 
class EncapsulationTest 
{ 
 public static void main(String[][] args) 
 { 
   Student st = new Student(); 
    st.id = "2"; // As the field is not private, so anyone can access it from outside the class. 
 } 
}

Now, what will happen?

Whenever id has been used, then the compilation time error will be generated.


Let’s understand how encapsulation allows modifying the implemented Java code without breaking other code who have implemented the code?

Since the data type of Id has been changed from string to integer, so we will only change in the getter and setter method to avoid breaking of other codes. Look at the program source code.

Program code 4:

package encapTest; 
class Student
{     
  Integer id;      
  public String getId()
  {          
    return String.valueOf(id);// String valueOf() method converts from int to String. It converts int to String, long to String, boolean to String, character to String, float to String, double to String.          
  } 
public void setId(String id)
{    
  this.id = Integer.parseInt(id); // Integer parseInt() method converts String into integer.     
 } 
} 
public class EncapsulationTest
{   
 public static void main(String [][] args)
 {      
   Student st = new Student();      
    st.setId("2");      
   System.out.println("Student ID: " +st.getId());     
   } 
  } 
Output:             
            2

Key Points to Remember:

1. Encapsulation is one of the four principles of OOPs concepts and the other three are Abstraction, Inheritance, and Polymorphism.
2. OOPs concepts in Java programming are implemented through four principles. They are:

  • Encapsulation (protecting data of a class from being accessed by members of another class).
  • Abstraction (Hiding data of class from other classes)
  • Inheritance (Using code written in a class inside other classes)
  • Polymorphism (Using various methods with the same name)

More on Encapsulation:


In this tutorial, we have covered almost all important points related to encapsulation in Java with the help of realtime examples and programs. Hope that you will have understood the basic definition of encapsulation and practiced all example programs. In the next, we will understand inheritance in Java, which is another important OOPs concept in Java programming.
Thanks for reading!!!

⇐ PrevNext ⇒

Please share your love