Scientech Easy Encapsulation in Java | Real Time Examples & Advantages | Scientech Easy

Tuesday, August 14, 2018

Encapsulation in Java | Real Time Examples & Advantages

encapsulation,java encapsulation,what is encapsulation in java,encapsulation in java with example,encapsulation in object oriented programming,encapsulation in oops,data encapsulation in java,example of encapsulation in java

Encapsulation in Java

Encapsulation means Data hiding or Protecting anything. It is one of the four principles of OOPs concepts in Java and the other three are Abstraction, Inheritance, and Polymorphism.
Encapsulation in Java is a technique of making the fields private in the class and providing the access to that field via the public method. For example Capsule i.e. capsule basically, encapsulate several combinations of medicine.
 What is Encapsulation?, Java Encapsulation with Real time examples
Let's consider capsule. If combinations of medicine are variables and methods then the capsule will act as a class and the whole process is called Encapsulation.
School bag is one of the most real examples of Encapsulation. School bag can keep our books, pens etc.

Thus, we can say that Encapsulation is actually the process of binding data members and methods together in a single unit. If the field is declared private in the class then it cannot be accessed by anyone from outside the class and hides the field within the class. Therefore, it is also called data hiding. 
Note: Each class in java itself is an example of encapsulation.

Let's understand Encapsulation in java by taking Real-time examples.

First Real-time example: 

When you log into your email account such as Gmail, Yahoo mail, Rediff mail etc then 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 then they are retrieved in an encrypted form and verified and then you are given the access to your account. You do not have control over it that how the password is verified and this keeps it safe from misuse.

Second Real-time Example:

Suppose you have an account in the bank. If your balance variable is defined as a public variable in the bank software then your account balance will be known public then, in this case, anyone can know your account balance. So do you like it? Obviously No. 
   So for making your account safe, they declare balance variable as private so that anyone cannot see your account balance and the person who have to see account balance then they will have to access private members only through methods defined inside that class and this method will ask your account holder name or user Id, or password for authentication. 
Thus, security is achieved by utilizing the concept of data hiding. This is called Encapsulation.

How to achieve Encapsulation in java? 


How to implement Encapsulation in java?

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.

Since getter and setter methods are widely used in Java programming but not everyone understands and implements these methods properly.  So I would like to understand about getter and setter methods clearly.

What are getter and setter methods?

In Java. the setter method is a method which is used for updating values of a variable. This method is also known as mutator method. Whereas getter method is a method which is used to retrieve the value of a variable or return the value of the private member variable. This method is also known as an accessor method. 

Let's take an example to understand getter and setter methods clearly. In this example simply we are making a class representing student with private variable and a couple of getter and setter methods.
Program 1:

public class Student{  
private String name;
    public String getName(){
      return name;
    public void setName(String studentName){
The class declares a private variable name. So the code from outside the class cannot be accessed directly, like this:

Student obj=new Student();"Amit"; // Compilation error. Since name is private.
String; //same as above.
So to remove the compilation error from the above code, we have to call the getter, getName() and the setter setName() to read and update the variable, like this:

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. 
Output: Amit
Thus, setter method is used to update the value of a variable. whereas getter method is used to read the value of a variable.

The naming convention of getter and setter:

The naming of setter and getter should follow Java bean naming convention as follows:
   getXxx() and setXxx() 
where Xxx is the name of the variable. 
For example: If the variable is the type of int 
private int number;
then appropriate getter and setter will be:
public getNumber()  { }
public void setNumber(int number)  { }

If the variable is a type of boolean then
private boolean rich;
public getRich()  { }
public void setRich(Boolean rich) { }

Program 2: In this example, all three data fields are private and which cannot be accessed directly. These methods can be accessed via public methods only. Fields stdName, stdRoll, and stdId are made hidden data field using Encapsulation technique of OOPs concepts.

package collegeStudent;
public class Student {
// Step 1: Declare the variable private which you want.
private String stdName; // private field.
private int stdRollNo;
private int stdId;
// Step 2: Apply the public getter method for each private vairable using the naming
        public String getStdName(){ // private field accessed inside 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 using the naming
        public void setStdName(String name){
        public void setStdRollNo(int rollNo){
        public void setId(int id){
public class EncapsulationTest{
   public static void main(String[][] args){
// Step 4: Create the object of class Student by using the new keyword. Here, obj is the 
           reference variable of class student and pointing to the object of the class student.
    Student obj=new Student();
// Step 5: Call setter method and set the value of variables.
// Step 6: Call 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());

Student Name: Kiran
Student Roll no: 4
Student Id: 12345

What would happen if you don't use Encapsulation?
If you don't use encapsulation then fields will not be private and could be accessed by anyone from outside the class. For example:
Program 3: Impact of not using encapsulation:

package college;
class Student {
String id; // No encapsulation since field is not private.
public class EncapsulationTest {
   public static void main(String[][] args){
   Student st=new Student();"2"; // As field is not private so it can be accessed by anyone from outside the class.
Suppose in above program 3, anyone changes the data type of id from String to Integer like this:

packege collegeStudent;
class Student{
  Integer id; // No encapsulation. since field is not private.
class EncapsulationTest{
public static void main(String[][] args){
Student st=new Student();"2"; // As field is not private so it can be accessed outside the class.

 then what will happen?  
Whenever Id has been used then the compilation error will be generated. 
Program 3: Let's understand how Encapsulation allow modifying implemented Java code without breaking others code who have implemented the code?
Since data type of Id has been changed from String to Integer so I will only change in getter and setter method to avoid breaking of other codes.

package college;
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){; // Integer parseInt() method convert String into integer.
public class EncapsulationTest{
  public static void main(String [][] args){\
Student st=new Student();
     System.out.println("Student ID: " +st.getId());
 Output: 2

Advantages of Encapsulation:

The encapsulated code is more flexible and easy to change with new requirements.
Encapsulation prevents the other classes to access the private fields.
Encapsulation allows modifying implemented code without breaking others code who have implemented the code.
It keeps the data and codes safe from external inheritance.
If you don't define setter method in the class then the fields can be made read-only.
If you don't define getter method in the class then the fields can be made write-only.
Encapsulation also helps to write the immutable class in java which is the good choice in multithreading.

Final words:

I hope this article will help you to understand about Encapsulation in Java with Real examples and its Advantages. Encapsulation is the very important topic in Java. It is always asked in Interview. You should understand mainly getter and setter methods to implement the encapsulation.
More on Encapsulation:
1. Best Encapsulation Programming Practice.
2. Encapsulation Interview Questions and Answers.

Next ➝Real-time Encapsulation Interview Questions                                           Scientech Easy loves you