Java Encapsulation

What is Encapsulation in java?

Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safes from outside interference and misuse. It is important to declare this class as private. It is also used for Data Hiding.

Without Encapsulation :

Code:

Java Code

class Area {

  // fields to calculate area
  int length;
  int breadth;

  // constructor to initialize values
  Area(int length, int breadth) {
    this.length = length;
    this.breadth = breadth;
  }

  // method to calculate area
  public void getArea() {
    int area = length * breadth;
    System.out.println("Area: " + area);
  }
}

class Main {
  public static void main(String[] args) {

    // create object of Area
    // pass value of length and breadth
    Area rectangle = new Area(4, 2);
    rectangle.getArea();
  }
}

Output : Area 8

Here, data can be accessed outside of the class also and that’s why this code is not secure. Our main aim is to make our data securable and here data hiding comes into the picture. The basic difference between encapsulation and data hiding is that encapsulation is a way of bundling data whereas hiding prevents external unauthorized access to the sensitive data. Access modifiers are used to achieve data hiding.

Data Hiding:

class Employee {
// private variables
 private String name;
 private int age;
 private int salary;
}

In the above code we successfully created our variables private, but how do we get and set the values? Let’s see our normal implementation:

Code:

Java Code

public class Tuf {
// private variables
   private String name;
 }

public class Main {
  public static void main(String[] args) {
  //object of class Tuf
    Tuf newObj = new Tuf();
    newObj.name = "Tuf";  
    System.out.println(newObj.name); //error
  }
}

Output Expectation: Tuf

Reality:

Tuf.java:10: error: name has private access in Tuf
    newObj.name = "Tuf";  
          ^
Tuf.java:11: error: name has private access in Tuf
    System.out.println(newObj.name); 
                             ^
2 errors
error: compilation failed

So, how can we solve this?

  • For handling this, we have getter and setter methods
  • The getter method returns the value of the field whereas the setter method updates or sets the value of the field.

With Encapsulation:

  • Here, we will see data hiding example,
  • With public getter and public setter to read and modify/set the values of the above-said fields.

Code:

Java Code

class Student {
    private int Student_Id;
    private String name;
    //getters, setters for Student_Id and name fields.
    public int getId() {
        return Student_Id;
    }
    public void setId(int s_id) {
        this.Student_Id = s_id;
    }
    public String getname() {
        return name;
    }
    public void setname(String s_name) {
        this.name = s_name;
    }
}
class Main{
    public static void main(String[] args) {
        //create an object of Student class
        Student s=new Student();
        //set fields values using setter methods
        s.setId (27);
        s.setname("TUF Student");
        //print values using getter methods        
        System.out.println("Student Data:" + "\nStudent ID:" + s.getId()
                            + " Student Name: " + s.getname());
    }
}

Output :

Student Data:

Student ID:27 Student Name: TUF Student

  • it cannot be accessed from outside the class.
  • In order to access, we have used public methods: getId() and setId(). These methods are called getter and setter methods.
  • Here, the student Id and name which is not accessible outside the class are data hiding.

Why should we use Encapsulation?

  • Anything which can be changed and is bound to change soon is an up-and-comer of Encapsulation. This additionally assists with composing a more unambiguous and strong code.
  • The getter and setter methods provide read-only or write-only access to our class
  • Encapsulation is used to bind the fields and methods together. It mainly aims at hiding the data and controlling access to it. 

Advantages of Encapsulation:

  • Encapsulated Code is more flexible and easy to change with new requirements.
  • Encapsulation allows you to change one part of code without affecting other parts of code.
  • It helps to control the values of our data fields. (always private)
  • Provides Getter and Setter methods.
  • A class can have complete control over its data members and data methods.

Special thanks to Amisha Kumari for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article