Encapsulation in Java

Encapsulation in Java

Encapsulation in java is the process of hiding internal detail from the outside world and accessing it only through publicly exposed method is data encapsulation / data binding.

Example of encapsulation in java -

The common example of encapsulation is capsule. In capsule all medicine are encapsulated in side capsule.

how to implement encapsulation in java
Source - sitebay

Benefits of encapsulation -

Provides abstraction between an clients and object.
Restrict unwanted clients to access an object.
Example: A bank application restrict client to change an Account's balance.

How to implement Encapsulation Java ?

  • by declaring variables as private, to restrict it from direct access.
  • by clicking one pair of public setter and getter methods to access private variables.
  • We declare variable as private to stop accessing them directly from outside class.

We define public method to access the same variable from outside class with proper validation because if we provide variable access directly we can't validate data.

Setter method for setting or modifying variable value, Getter method for getting or accessing variable value.

Setter method are called as mutator method and Getter metod is called as assessor method.

//Bank.java
public class Bank {

//hiding class data
private double balance;

private void setBalalnce(dobule balance) {
//validation logic
this.balance = this.balance + balance;
}

public double getBalance() {
//add validation logic
return balance;
}
}


//BankUser.java
class BankUser {
public static void main(String [] args) {
Bank anz = new Bank();
anz.setBalance(500000);
System.out.println(anz.getBalance()); 
}
}

In above example balance data members are private, which cannot be accessed directly. These fields can only be accessed via public methods only. Field balance are made hidden data fields using encapsulation technique of OOPs.

Problem without Encapsulation -

If we declare balance variable as public in Bank class then Bank class will access balance variable directly and can assign any value which is illegal as per the Bank Object.

Leave a Comment

%d bloggers like this: