Encapsulation

 

Encapsulation

To encapsulate something is to enclose something, in our case, we encapsulate or wrap data into a single unit essentially binding the data and code together.

 

i. Get and set methods:

We use set method to set value of variable and get method to get the value of variable.


Example:


// filename: Example6.java

public class Example6 {
    private String name; 
    private int age; 

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

      // Setter Methods
    public void setName(String newName) {
        this.name = newName;
    }
    public void setAge(int newAge) {
        this.age = newAge;
    }
}

 

Here we have get method that takes values of variables and set method that assigns arguments as values to these variables.


//Filename: Example5.java

public class Example5 {

    public static void main(String[] args) {
        Example6 ex6 = new Example6();
        ex6.setName("Maxon"); 
        ex6.setAge(26);
        System.out.println("Name: " + ex6.getName());
        System.out.println("Age: " + ex6.getAge());
    }
}

 

Here, we make object of class Example6. Let’s run this file.


Output:


Name: Maxon
Age: 26

 

Advantages of Encapsulating data:

  • We can hide our data more efficiently. Hence, after implementation, user will not have any idea about the inner working of the class. To the user, only setting and initializing values is visible.
  • It makes our data reusable.
  • Encapsulated data is easy to test.

 

Disadvantages of Encapsulating data:

  • Size of the code increases exponentially.
  • As the size of the code increases, we need to provide additional implementation for each method.
  • We provide additional methods, this increases code execution.