Encapsulation in Java

Encapsulation in Java

In this article, I am going to discuss Encapsulation in Java with Examples. Please read our previous where we discussed Polymorphism in Java. At the end of this article, you will understand the following pointers in detail.

  1. What is Encapsulation?
  2. Need of Encapsulation in Java
  3. Difference Between Data Hiding and Encapsulation in Java
  4. How to achieve Encapsulation in Java?
  5. Understanding Getter and Setter Methods in Java
  6. Program with and without Encapsulation
  7. Advantages of Encapsulation in Java
What is Encapsulation?

The meaning of Encapsulation is to make sure that “sensitive” data is hidden from users. Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. If a data member is private it means it can only be accessed within the same class. No outside class can access private data members (variable) of other classes. For better understanding please have a look at the following image.

Encapsulation in Java with Real-time exampels

Need of Encapsulation in Java:
  • Better control of class attributes and methods.
  • Encapsulation helps us to keep related fields and methods together, which makes our code cleaner and easy to read.
  • Helps us to achieve a loose couple.
  • An object exposes its behavior by means of public methods or functions.
  • Increased security of data.
What is Data Hiding?

Data hiding was introduced as part of the OOP methodology, in which a program is segregated into objects with specific data and functions. This technique enhances a programmer’s ability to create classes with unique data sets and functions, avoiding unnecessary penetration from other program classes. Encapsulation refers to the bundling of related fields and methods together. This allows us to achieve data hiding. Encapsulation in itself is not data hiding. Please have a look at the following image for a better understanding.

Data Hiding in Java

Difference Between Data Hiding and Encapsulation in Java:
  • Data hiding only hides class data components, whereas data encapsulation hides class data parts and private methods.
  • Data hiding focus more on data security and data encapsulation focuses more on hiding the complexity of the system.
How to achieve Encapsulation in Java?

To achieve encapsulation in Java, you need to:

  • declare class variables/attributes as private
  • provide public getter and setter methods to access and update the value of a private variable
Getter and Setter Methods in Java :
  • The get method returns the variable value, and the set method sets the value.
  • If a data member is declared “private”, then it can only be accessed within the same class. No outside class can access data members of that class. If you need to access these variables, you have to use public “getter” and “setter” methods.
  • Getter and Setter’s methods are used to create, modify, delete, and view the values of the variables.
  • The syntax for both is that they start with either get or set, followed by the name of the variable, with the first letter in upper case.
  • In Java getters and setters are completely ordinary functions. The only thing that makes them getters or setters is a convention.
  • A getter for demo is called getDemo and the setter is called setDemo .
  • It should have a statement to assign argument value to the corresponding variable.
Sample Program for Encapsulation using Get and Set Method:

The following example is self-explained. So, please go through the comment lines.

package Demo;

public class EncapsulationDemo {
 // private variables declared  
    // these can only be accessed by  
    // public methods of class 
    private String Name; 
    private int RollNo; 
    private int Age; 
  
    // get method for age to access  
    // private variable Age 
    public int getAge()  
    { 
      return Age; 
    } 
   
    // get method for name to access  
    // private variable Name 
    public String getName()  
    { 
      return Name; 
    } 
      
    // get method for roll to access  
    // private variable RollNo 
    public int getRoll()  
    { 
       return RollNo; 
    } 
   
    // set method for age to access  
    // private variable Age 
    public void setAge( int newAge) 
    { 
      Age = newAge; 
    } 
   
    // set method for name to access  
    // private variable Name 
    public void setName(String newName) 
    { 
      Name = newName; 
    } 
      
    // set method for roll to access  
    // private variable RollNo 
    public void setRoll( int newRollNo)  
    { 
      RollNo = newRollNo; 
    } 
  public static void main (String[] args)  
    { 
        EncapsulationDemo obj = new EncapsulationDemo(); 
          
        // setting values of the variables  
        obj.setName("Harsh"); 
        obj.setAge(19); 
        obj.setRoll(51); 
          
        // Displaying values of the variables 
        System.out.println("Student's Name: " + obj.getName()); 
        System.out.println("Student's Age: " + obj.getAge()); 
        System.out.println("Student's RollNo: " + obj.getRoll()); 
               
    } 
}

Output:

Encapsulation in Java

What is the problem if we don’t follow encapsulation in Java while designing a class?

If we don’t the encapsulation principle while designing the class, then we cannot validate the user given data according to our business requirement as well as it is very difficult to handle future changes. If we don’t use encapsulation, the fields will not be private and could be accessed by anyone from outside the class.

Sample Program without Encapsulation in Java:

Let’s create a program where we will understand the impact of not using the encapsulation technique.

package Demo;

public class Account {
 int account_number; // Here, No encapsulation is used. Since the field is not private. 
        int account_balance; 
        public void deposit(int a) 
        {
           if (a < 0) {
               System.out.println("Insufficient Balance"); 
           } 
           else
              account_balance = account_balance + a;
       }
}

Suppose in the above program, a hacker managed to gain access to the code of your bank account. He tries to do a deposit of an amount of -100 by using the “deposit” method.

package Demo;

public class Account {
 int account_number; // Here, No encapsulation is used. Since the field is not private. 
        int account_balance; 

        public void deposit(int a) {
          if (a < 0) {
              System.out.println("Insufficient Balance"); 
          } 
          else
            account_balance = account_balance + a;
        }
}
class Hacker{
 public static void main(String args[]) {
 Account acc = new Account();
 acc.account_balance = -100;
 acc.deposit(-100);// As the field is not private. So, it can be accessed by anyone from outside the class. 
 }	
}
Now, what will happen? 

As Method implementation has a check for negative values. So the approach fails.

Sample Program: With Encapsulation

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

Since the hacker tries to deposit an invalid amount,i.e. -100. So I will set a variable in a class as “private”. So that it can only be accessed with the methods defined in the class. No other class or object can access them. If you need to access these variables, you have to use public “getter” and “setter” methods.

package Demo;

public class Account {
 private int account_number; 
        private int account_balance; 

        // getter method
 	public int getBalance() {
          return this.account_balance;
        }
 	public int getNumber() {
          return this.account_number;
        }

        // setter method
 	public void setBalance(int num) {
          this.account_balance = num;
        }
 	public void setNumber(int num) {
          this.account_number = num;
        }

        public void deposit(int a) {
          if (a < 0) {
              System.out.println("Amount should be more than 0."); 
          } else
            account_balance = account_balance + a;
       }
}
class Hacker{
 public static void main(String args[]) {
 Account acc = new Account();
 acc.setBalance(-100);
 acc.deposit(-100);
 System.out.println("Account Balance is : " +acc.getBalance()); 
 }	
}

Output: Amount should be more than 0.

Advantages of Encapsulation in Java:
  • Encapsulated code is easy to test for unit testing.
  • It improves the maintainability and flexibility of the code.
  • With Java Encapsulation, you can hide (restrict access) to critical data members in your code, which improves security.
  • It also improves the re-usability and easy to change with new requirements.
  • The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields.

In the next article, I am going to discuss Access Modifiers in Java with examples. Here, in this article, I try to explain Encapsulation in Java with examples. I hope you enjoy this Encapsulation in Java with examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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