Friday, September 28, 2018
Home > java > Encapsulation in Java

Encapsulation in Java

Before going to the topic of encapsulation in java. First, we must know what is encapsulation? In general, encapsulation is the process or action of enclosing something to a wrapper. It is just like we have a capsule which itself encloses different medicines or a mixture of medicines.

Encapsulation is one of the four pillars of OOP. In programming languages encapsulation is the process of combining the code and data in a single unit. So encapsulation in java is the process in which we wrap the code and data. I.e. the data members and the functions that provide access or can modify/manipulate those data members are put together in a single unit known as class.

In Java, the basis of encapsulation is a class. And a perfect example of encapsulation in java is a Java Bean class.

Another way of thinking about encapsulation is that it is a shield around the data that prevents the data to be accessed by the code outside this shield. In encapsulation, the data members or variable of the class are hidden from any other class. They can only be manipulated through the functions (getters and setters) provided within the class to manipulate them. We achieve encapsulation in java by keeping all the data members private and their getters and setters as public so they can provide access outside the class to these data members. And of course, this means that the public interface of the class is designed in such a way that it should not expose much of the information about the private interface of the class or the inner working of the class.

encapsulation in java

Advantages of encapsulation in java

Data Hiding: The very first advantage of encapsulation in java is information hiding. I.e. the end user doesn’t know about the implementation details.

Flexibility: As we can define the getters and setters of a class. So by defining any one of these, we can make a variable read-only or write-only.

Control: It provides control over the data. E.g. If we don’t want to store a negative value in a variable we can check for that in the setter of the variable.

Easy Testing: The testing of an encapsulated class is also easy.

Easy to create: Different IDEs also provide the facility to auto-generate the getters and setters of the data member, so we can easily create an encapsulated class in those IDEs.

Disadvantages of encapsulation in java

Talking about the advantages of encapsulation in java. It can lead us to bad designing if we don’t follow encapsulation properly.

Information Hiding

Sometimes we may refer to encapsulation as information hiding. Let us consider stack (a data structure) as an example of encapsulation. In the real life, we can consider stack as the pile of dishes. As whenever we place a dish on the pile, we always place the dish at the top, similarly whenever we insert a value (push) to the stack it is always at the top. Similarly, when we need to get a value (pop) from the stack it always gives us the top value. The stack data structure follows the LIFO rule. A programmer can create a stack using arrays or linked lists. The end user doesn’t need to know the implementation details of the stack. Whether it is made by using arrays or linked list. So the programmer can hide the implementation details of the stack thus achieving the encapsulation (information hiding).

Considering encapsulation as information hiding functions also provide this concept. As the calling program does not know how the function is actually performing the task.

Let’s have a look at a simple program to understand more about it.

package example;
public class Person {

       private String name;
       private int age;

       //getters and setters.

       public int getAge() {
              return age;
       }
       public String getName() {
              return name;
       }
       public void setAge(int age) {
              age = age;
       }
       public void setName(String name) {
              name = name;
       }
}

We have used public getters and setters (getAge, getName, setAge, setName) to access the members of the Person class.  Any class that wants to access the variables should access them through these getters and setters.

You can access the variables of the Person class using the following program −

package example;
public class RunPerson {
       public static void main(String args[]) {
              Person p = new Person();
              p.setName("Jan Doe");
              p.setAge(23);
              System.out.print("Name : " + p.getName() + " Age : " + p.getAge());
       }
}

This above example will produce the following result −

Output

Name : Jan Doe Age : 23

Best way to achieve encapsulation in java that we should try to use local variables as much as possible in our programs.

As we mentioned earlier in the advantages of encapsulation that we can make a class read-only or write-only as well. So here is the simple example of read-only and write-only classes. Using the above class person

Read-Only Class

package example;
public class PersonOne {
       private String name = “Jan Doe”;
       private int age = 23;
     
      //getters for the variables. An example of Read-Only class.

       public int getAge() {
              return age;
       }
       public String getName() {
              return name;
       }
}

The Program to use the above class is:

package example;
public class RunPerson {
       public static void main(String args[]) {
              PersonOne p1 = new PersonOne ();
               /* These below two lines will give us the compile time error
              as we have made our class read-only. */
              
              p1.setName("Jan Doe jr.");
              p1.setAge(20);

              // To get the output we should remove or comment the above two statements.
              System.out.print("Name : " + p.getName() + " Age : " + p.getAge());
       }
}

Removing those two lines will give us the following output.

Name : Jan Doe Age : 23

Write-Only Class

package example;
public class PersonTwo {
       private String name;
       private int age ;

       //Setters for the variables. An example of Write-Only class.

       public void setAge(int age) {
              age = age;
       }
       public void setName(String name) {
              name = name;
       }
}

The Program to use the above class is:

package example;
public class RunPerson {
       public static void main(String args[]) {
              PersonTwo p1 = new PersonTwo ();     
              p1.setName("Jan Doe jr.");
              p1.setAge(20);
           
              /* This below line will give us compile time error as we have made our class write-only. 
              To get the output we should provide getters of the members variables of the class.*/
              System.out.print("Name : " + p.getName() + " Age : " + p.getAge());
       }
}

 

Now let’s have a look at a more precise example in which we can check if the value from the user is correct or not.

package example;
public class Account {
       private String title;
       private double balance;
       private static String account_number;
       private static int i = 1;

       Account() {
              title = "";
              balance = 0.0;
              account_number = "AN-" + i++;
       }

       // public getters and setters to access the data members outside the class.

       public String getTitle() {
              return title;
       }
       public void setTitle(String title) {
              this.title = title;
       }
       public double getBalance() {
              return balance;
       }
       public void setBalance(double balance) {
              /*
              * here we are checking that if the amount entered by the client class
              * is greater than 0 only then add that amount to the previous balance.
              * otherwise set it to previous balance.
              */
              if (balance > 0) {
                     this.balance = this.getBalance() + balance;
              } else {
                     this.balance = this.getBalance();
              }
       }
       
       // making account number as read-only. Because we cannot change account number.

       public String getAccount_number() {
              return account_number;
       }
}

 

To make use of this above class. We use the following simple scenarios.

package example;
public class TestAccount {
       public static void main(String args[]) {

              Account acc1 = new Account();
              acc1.setTitle("Jan Doe");
              acc1.setBalance(100);
              System.out.println("Title : " + acc1.getTitle() + " Account Number : " + acc1.getAccount_number() + " Balance : "+acc1.getBalance());
       }
}

The above usage will give us the following Output.

Title: Jan Doe Account Number: AN-1 Balance: 100.0

package example;
public class TestAccount {
       public static void main(String args[]) {

              Account acc1 = new Account();
              acc1.setTitle("Jan Doe");
              acc1.setBalance(100);

              System.out.println("Title : " + acc1.getTitle() + " Account Number : " + acc1.getAccount_number() + " Balance : "+acc1.getBalance());

              // trying to save a negative value
              acc1.setBalance(-50);

              System.out.println("Title : " + acc1.getTitle() + " Account Number : " + acc1.getAccount_number() + " Balance : "+acc1.getBalance());
       }
}

This will generate the following output.

Title: Jan Doe Account Number: AN-1 Balance: 100.0

// After trying to save the negative value.

Title: Jan Doe Account Number: AN-1 Balance: 100.0

package example;
public class TestAccount {
       public static void main(String args[]) {

              Account acc1 = new Account();
              acc1.setTitle("Jan Doe");
              acc1.setBalance(100);

              System.out.println("Title : " + acc1.getTitle() + " Account Number : " + acc1.getAccount_number() + " Balance : "+acc1.getBalance());

              Account acc2 = new Account();
              acc2.setTitle("Phill Smith");
              acc2.setBalance(320);

              System.out.println("Title : " + acc2.getTitle() + " Account Number : " + acc2.getAccount_number() + " Balance : "+acc2.getBalance());
       }
}

Giving us the following output.

Title: Jan Doe Account Number: AN-1 Balance: 100.0

Title: Phill Smith Account Number: AN-2 Balance: 320.0

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.