Encapsulation in Java

Encapsulation in Java

This article covers an important OOP principle: encapsulation.

ยท

3 min read

Table of contents

No heading

No headings in the article.

In a previous article, we talked about how in Java , it is advisable to have the member variables be private and the methods public. This is because it prevents users and other classes from interfering with the data in the class. It also allows for interfaces (methods) to interact with the private member variables without being able to directly change their values. This enhances the robustness and security of the software we write.

This is essentially what encapsulation is. Encapsulation implements an important concept in Java known as data hiding.

Data hiding is a software development technique that separates the internal details of a class from its external interface. This allows users of the class to interact with it without knowing how it works internally. This can improve the flexibility, maintainability, and security of the code

It is achieved by declaring class members as private. This means that they can only be accessed by methods within the same class. Public methods can be used to provide controlled access to the private members of a class whether they are getters, setters, or custom methods.

Data hiding has several benefits, including:

  • Increased security: Data hiding prevents unauthorized access to class data. This can help to protect sensitive data, such as passwords and credit card numbers.

  • Improved performance: Data hiding can improve performance by reducing the need for data copying. When a class member is declared as private, the compiler can generate code that directly accesses the member, without the need to copy it to a public variable.

  • Increased flexibility: Data hiding can make classes more flexible and reusable. By hiding the implementation details of a class, other classes can be written that depends on the class without knowing how it works internally. This makes it easier to change the implementation of a class without affecting other classes that depend on it.

With this context, we can now further expand on encapsulation. Encapsulation in OOP refers to binding the data and the methods to manipulate that data together in a single unit (class). Encapsulation is normally done to hide the state and representation of an object from the outside. A class can be thought of as a capsule having methods and data members inside it.

class User {

  // Private fields
  private String userName;
  private String userEmail; 
  private String password;     

  //Parameterzied constructor to create a new user
  public User(String userName, String userEmail, String password) {    
    this.userName = userName;
    this.userEmail = userEmail;
    this.password = password;
  }

  public void login(String userEmail, String password) {
    //Check if the username and password match
    if (this.userEmail.toLowerCase().equals(userEmail.toLowerCase()) && this.password.equals(password)) { 
    // toLowercase() converts all the characters to lowercase & equals() checks if the two strings match

    System.out.println("Welcome: " + this.userName);
    }
    else System.out.println("Invalid Login!"); 
  }

}

class Main {

  public static void main(String[] args) {
    User showwcase = new User("ricky123", "ricky@gmail.com","xyzab"); //Creates a new user and stores the username, email and password

    showwcase.login("ricky@gmail.com","xyzab"); //Grants access because login credentials match

    showwcase.login("ricky@gmail.com", "xyz"); //Does not grant access because the credentials are invalid

    //showwcase.password = "xyz123"; // Uncommenting this line will give an error. Fields of User class cannot be accessed
  }

}

As you can see encapsulation is very important. It sets very strict rules on who can access your code, how they can access it, and the level of access. ๐ŸŽฏ

ย