Java-Encapsulation

Encapsulation (data Hiding) simply means binding object state(fields) and behaviour(methods) together. If you are creating class, you are doing encapsulation. In this guide we will see how to do encapsulation in java program
The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class.

Simple Example of Encapsulation in Java

How to implement encapsulation in java:
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.

User Pojo Class


package com.ahold.scanit.datamigration;

//A User class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
public class User {
// private data members
private String userName;
private String mobile;
private String email;
private String pan;

// public getter and setter methods
public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPan() {
return pan;
}

public void setPan(String pan) {
this.pan = pan;
}
}

Test Class

package com.ahold.scanit.datamigration;

//A Java class to test the encapsulated class User.
public class TestUser {

public static void main(String[] args) {
// creating instance of User class
User user = new User();
// setting values through setter methods
user.setEmail("sibinmuhammed@gmail.com");
user.setMobile("8075-888888");
user.setPan("CDXRETQ");
user.setUserName("sibin");
// getting values through getter methods
System.out.println(user.getEmail() + " " + user.getMobile() + " " + user.getPan() + " " + user.getUserName());
}
}

Output:

sibinmuhammed@gmail.com 8075-888888 CDXRETQ sibin

Advantages of Encapsulation in Java
  • Encapsulation is binding the data with its related functionalities. Here functionalities mean "methods" and data means "variables"
  • So we keep variable and methods in one place. That place is "class." Class is the base for encapsulation.
  • With Java Encapsulation, you can hide (restrict access) to critical data members in your code, which improves security
  • As we discussed earlier, if a data member is declared "private", then it can only be accessed within the same class. No outside class can access data member (variable) of other class.
  • However, if you need to access these variables, you have to use public "getter" and "setter" methods.

Comments