Java Encapsulation

In this lesson of our Java course, we will learn about the Java encapsulation. We will learn about the encapsulation in Java using some examples.

1. Java Encapsulation

Java encapsulation is one of the key feature of Java object-oriented programming. It is one of the four fundamental of Object-Oriented Programming (OOP)

  1. Polymorphism.
  2. Inheritance.
  3. Abstraction
  4. Encapsulation

Encapsulation in Java is the process by which we wrap the variables and methods together inside a single class. With Java encapsulation, the variable defined inside the class is hidden from other classes and may be accessed using though the method defined in the class. The process of wrapping these inside the class is also known as data hiding.

In a simple term, encapsulation helps us hide the details of an object from outside of the class and the behavior is only exposed through the public methods. This can also help us change the internal details of the class, affecting no external system using our class or its methods.

2. Java Encapsulation Rules

Here are some simple rule to implement Java encapsulation:

  1. One of the core principle of Java encapsulation is to use private variables. This allows variables to be accessible only by the method of the class where they are declared.
  2. Add public getter and setter methods. This will ensure only these methods can read or write the variables defined in the class.
  3. Inner classes can encapsulate code. This can be useful if you want to hide the implementation of a method from other classes.

3. Java Encapsulation Example

Let’s look at the following example to understand the encapsulation in Java.

public class Customer {
    private String firstName;
    private String lastName;
    private String email;

    //no args constructor
    public Customer() {
    }

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
    public String getCustomerName() {
        return firstName + " " + lastName;
    }
}

In the above example, we defined the following 3 private variable:

  • firstName
  • lastName
  • email

Since all the three variables are private, they can only be accessed by the method defined inside the Customer class. The getName(), setName() and getCustomerName() and other methods are public. The private variables defined in the Customer class can only be accessed though these public methods from other classes. Here is an example of accessing these variable.

public class JavaEncapsulationExample {
    
    public static void main(String[] args) {
        //using getter and setter
        Customer cust = new Customer();
        cust.setFirstName("Ajay");
        cust.setLastName("Kumar");

        System.out.println("First name is:: "+cust.getFirstName());
        System.out.println(cust.getCustomerName());
        // create object of Customer
        // pass first name and last name
        Customer customer = new Customer("Ajay", "Kumar");
        System.out.println(customer.getCustomerName());
    }
}

If we run above example, we will see the following output

First name is:: David
David John
Ajay Kumar

If you try to use cust.firstName in JavaEncapsulationExample, you will see a compile time error. This shows that the private variables defined in the Customer class are not visible outside the class.

Java encapsulation
Don’t think encapsulation is always a data hiding. It’s not entirely true. Remember, Java encapsulation is wrapping related fields and methods together. This can achieve data hiding.

4. Benefits of Encapsulation

Java encapsulation is a key concept and has many benefits.

  • With encapsulation, we keep the fields and related methods together, this help to improve the code readability (all related fields in one place) and maintainability (we don’t have to make changes on multiple files).
  • The getter and setter provide a ready only and write only access point.
  • Hiding the data members of a class provides security as it only allows the data access and change through public methods. This can help to prevent data corruption and security breaches.
  • Encapsulation can make a system easier to understand by dividing it into smaller, more manageable units.
  • Abstraction: Encapsulation allows developers to abstract away the details of an object’s internal state and behavior, and only expose a well-defined set of public methods.

5. Data Hiding

It’s important to understand how data hiding works in Java, as it used more commonly with the encapsulation in Java. Data hiding is a way of restricting the access of our data members by hiding the implementation details.

public class Customer { 
    private String email;
    public String getEmail() {
        return this.email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}
public class JavaEncapsulationExample {
    public static void main(String[] args) {
        //using getter and setter
        Customer customer = new Customer();
        customer.setEmail("[email protected]");
    }
}

In the above example, we can’t access the private field email outside the class. The only way to access the email is using the public getEmail() or setEmail() methods. Making email private allowed us to restrict unauthorized access from outside the class. This is data hiding.

Summary

In this lesson, we learned about the Java encapsulation. Encapsulation is a key concept in Java and it provides maintainability, reliability and data security. As Always, the source code for this course in available on our GitHub repository.