Home » Java Basics » Encapsulation in Java

About Sotirios-Efstathios Maneas

Sotirios-Efstathios Maneas
Sotirios-Efstathios (Stathis) Maneas is a PhD student at the Department of Computer Science at the University of Toronto. His main interests include distributed systems, storage systems, file systems, and operating systems.

Encapsulation in Java

In this tutorial we will discuss about Encapsulation in Java. Encapsulation is the mechanism for restricting access to an object’s components. It aims for high maintenance and handling of the application’s code. Also, the encapsulation mechanism protects the members of a class from external access, in order to be protected against unauthorized access.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Also, encapsulation provides the ability to modify our implemented code without breaking the code of others who use our code. Thus, using encapsulation we can achieve maintainability, flexibility and extensibility of our code.

Encapsulation in Java

Java provides three keywords in order to define the scope and the access permissions of a class member or method: public, private and protected. A public member or method can be accessed from any other class. A private member or method is accessible only within its own class. Finally, a protected member is accessible within its class, its sub-classes and in all classes that reside in the same package.

A sample example of encapsulation in Java is shown below:


public class User {

     private String username = null;
     private String password = null;
     private String firstname = null;
     private String lastname = null;
     private String email = null;

     public User(String username, String password, String firstname, String lastname,
                        String email) {
          this.username = username;
          this.password = password;
          this.firstname = firstname;
          this.lastname = lastname;
          this.email = email;

     // Define all setter and getter methods for each member field.
     public String getUsername() {
          return username;

     public void setUsername(String username) {
          this.username = username;

     public String getPassword() {
          return password;

     public void setPassword(String password) {
          this.password = password;

     public String getFirstname() {
          return firstname;

     public void setFirstname(String firstname) {
          this.firstname = firstname;

     public String getLastname() {
          return lastname;

     public void setLastname(String lastname) {
          this.lastname = lastname;

     public String getEmail() {
          return email;

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

     public String toString() {
          return "<" + username + ", " + password + ", " + email + ", "
                        + firstname + ", " + lastname + ">";

In this example, we created a User class that contains the username, password, email, first and last names of a user of our application. As we observe, all members of the User class are declared as private. For each member we provide a setter and a getter method, in order to change and retrieve the value of a member respectively.

The functionality of a User instance is implemented inside its class. A very important feature of encapsulation is the ability to change the implementation of a method, without changing the provided API. Also, if we want to alter or extend the functionality of a User, all changes will be applied in this class only. Thus, the extensibility and maintainability of our code increase.

A sample main method that creates and handles instances of the User class is shown below:

public static void main(String[] args) {
     User user1 = new User("StathisJCG", "JavaCodeGeeks", "myemail", "Stathis", "Maneas");
     System.out.println("User: " + user1.toString() + "\n");

     System.out.println("My new username is: " + user1.getUsername() + "\n");

     System.out.println("My password is: " + user1.getPassword());
     System.out.println("I am about to change my password...\n");

     System.out.println("My new password is: " + user1.getPassword());

A sample execution of the main method is shown below:

User: <StathisJCG, JavaCodeGeeks, Maneas, myemail, Stathis>

My new username is: JCG

My password is: JavaCodeGeeks
I am about to change my password...

My new password is: JavaCodeGeeks!


Design Patterns and Encapsulation

The encapsulation mechanism is used by very popular design patterns, in order to provide a specific functionality. For example, the Factory Pattern aims for creating objects, without exposing the implementation logic to the client. On the other hand, the Singleton Pattern is used to ensure that at most one instance of a class will be created. Both these patterns are based on the encapsulation, in order to implement their functionality.

Final comments about Encapsulation

As we already mentioned, the encapsulation mechanism aims for controlling the access over the fields or methods of a class and for providing flexibility. Specifically, by using encapsulation while coding our applications, we:

  • Combine the data of our application and its manipulation in one place.
  • Allow the state of an object to be accessed and modified through behaviors.
  • Hide the implementation details of an object.
  • Reduce the coupling of modules and increase the cohesion inside them.
  • Create immutable classes that can be used in multi-threaded environments.

Finally, we must not confuse the encapsulation mechanism with the abstraction mechanism: the latter aims to specify what an object can do, while the former aims to specify how an object implements its functionality.

This was a tutorial about encapsulation in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Leave a Reply

Be the First to Comment!

Notify of