Java Encapsulation With Examples

Java Encapsulation With Examples

Encapsulation in Java -

To wrap up data, and function(Method) in a single entity. Known as class is called encapsulation.In other words

Access control is often referred to as implementation hiding. Wrapping data and methods within classes in combination with implementation hiding is often called encapsulation.

 Encapsulation creates new data types by combining characteristics and behaviors. Implementation hiding separates the interface from the implementation by making the details private. This sort of mechanical organization makes ready sense to someone with a procedural programming background.

How to achieve Encapsulation in java -

  • Declare the variables of a class as private.
  • Provide public Set(Write only), and get(Only read) methods to modify and view the values of the variables.

Example -

package javaLearnings;

class Encapsulation{
private int a;
private String name;
private int age;

//Getter and Setter methods
   public int geta(){
return a;

public String getname(){
return name;

public int getage(){
return age;

public void setage(int b){
       age = b;

public void setname(String c){
       name = c;

public void seta(int d){
       a = d;

public class Main {

public static void main(String[] args) {
// write your code here
       Encapsulation ob = new Encapsulation();
"Mukul Agrawal");
"Employee Name: " + ob.getname());
"Employee SSN: " + ob.geta());
"Employee Age: " + ob.getage());


Output -