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

Sunday, March 24, 2019

Encapsulation in Java | Real Time Examples & Advantages

Encapsulation in Java


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 encapsulate 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.
Encapsulation in Java
In the encapsulation technique, we declare the 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 the field within the class. Therefore, it is also called data hiding. 

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

Real-time Examples of Encapsulation in Java


Real-time Example 1:
School bag is one of the most real examples of Encapsulation. School bag can keep our books, pens etc.

Real-time Example 2: 
When you log into your email accounts such as Gmail, Yahoo mail, or Rediff 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 the 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.

Real-time 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, he 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, and password for authentication. 
Thus, We can achieve security by utilizing the concept of data hiding. This is called Encapsulation.
Key points:
In Java, Encapsulation is one of the four principles of OOPs concepts and the other three are Abstraction, Inheritance, and Polymorphism. 

How to achieve or implement Encapsulation in Java


We can achieve encapsulation in Java in the following ways.
1. Declaring the instance variable of the class as private. so that it cannot be accessed directly by anyone from outside the class.
2. Provide the public setter and getter methods in the class to set/modify the values of the variable/fields.

Advantages of Encapsulation in Java


There are following advantages of encapsulation in Java. 
1. The encapsulated code is more flexible and easy to change with new requirements.
2. It prevents the other classes to access the private fields.
3. Encapsulation allows modifying implemented code without breaking others code who have 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.

Disadvantages of Encapsulation in Java


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

Data Hiding in Java


An outside person cannot access our internal data directly or our internal data should not go out directly. This oops feature is called data hiding n Java.
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. It is highly recommended 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 tightly encapsulated class, we are not required to check whether 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?
1. class A 
    {
       private int x=20;
    }
    class B extends A
   {
       int y=50;
   }
    class C extends A
   {
      private int z=10;
    }
A. Class A and Class C are tightly encapsulated classes. Class A is not tightly encapsulated class because of non-private variable y. Anyone can access directly from outside the class.
2. class P
      {
         int a=10;
      }
     class Q extends P
     {
        private int b=20;
     }
     class R extends Q
     {
       private int z=30;
      }
A. 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 is 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: 
1. If the parent class is not tightly encapsulated, No child class is tightly encapsulated because parent class's non-private data members by default are available to every child class.
2. Thus, we can say that Data hiding, Encapsulation, and Tightly encapsulated class concepts are used for security purpose.

Java Encapsulation Example Programs


Let's see some practical example programs related to encapsulation in Java.
 Program source code 1:
    package encapsulation; public class Student{ private String name; public String getName(){ return name; } public void setName(String studentName){ name=studentName; } }
In this example program, we declare 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. } }
So, to remove the compilation error problem from the above code, we will have to call the getter, getName() and the setter setName() to read and update the variable like this.
    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
Program source code 2: 
In this example, all three data fields are declared as private which cannot be accessed directly from outside the class. These methods can be accessed via public methods only from outside the class. 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 variables private in the class. private String stdName; // private field. private int stdRollNo; private int stdId; // Step 2: Apply the public getter method for each private variable. public String getStdName(){ // Private fields can be accessed only 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. 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 the setter method and set the value 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, the fields will not be private and could be accessed by anyone from outside the class. Let's see a simple practical example program to understand what will happen?
Program source code 3: 
Impact of not using the encapsulation technique.
    package college; 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, 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:
    package collegeStudent; 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 field is not private so it can be accessed by anyone from outside the class. } }
Now, what will happen?  Whenever Id has been used then the compilation time error will be generated.
Program source code 4: 
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){ this.id=Integer.parseInt(id); // Integer parseInt() method convert 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
Hope that this article has covered almost all the important topics related to Encapsulation in Java with real examples and advantages. Encapsulation is a very important topic in Java. It is always asked in the Interview. We hope that you will have enjoyed this article.
Thanks for reading!