Encapsulation in Java

Remember capsule, how they have all ingredients and everything wrapped and hidden inside. It is same here.

Encapsulation in Java means data hiding. It is used to make sure that data is hidden and secured from users.


Why to use encapsulation?

  • To increase the security of data.
  • To make class instances read-only or write only.
  • To gain better control over class instances.

We must declare variable as private and get and set methods as public to access or update private variable.

What is get and set?

As we learnt that private instance has no access outside class. But we can access private instances using get and set methods.


get

This method is used to return value from private variable.
Syntax:

public <ReturnType> get<Variable> () {
    return statement
}


set

This method is used to assign value for private variable.
Syntax:

public void set<Variable> (<DataType> <NewVariable>) {
    <OldVariable> = <NewVariable>
}


It is convention that variable name with first letter as capital should be used with set and get methods. However you can use any identifier.

Examples:

Lets access private variable in another class using get method.
Code:

public class LearnEncapsulation { public static void main(String[] args) { Encap en = new Encap(); int num = en.getVal(); System.out.println(num); } } class Encap { private int val = 5; public int getVal() { return val; } }
Also a example of making variable read-only.
Output:
5


Lets see another example where we assigned private variable in another class.
Code:

public class LearnEncapsulation { public static void main(String[] args) { Encap en = new Encap(); en.setVal(4); en.display(); } } class Encap { private int val; public void setVal(int x) { val = x; } public void display() { System.out.println("Val = " + val); } }
Also a example of write-only. val can be used with new value inside Encap class only.
Output:
Val = 4


Now lets update and access value together.
Code:

public class LearnEncapsulation { public static void main(String[] args) { Encap en = new Encap(); en.setVal(4); int num = en.getVal(); System.out.println(num); } } class Encap { private int val; public void setVal(int x) { val = x; } public int getVal() { return val; } }
Output:
4


Objects in Java Previous Next Constructor in Java