Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

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:

User.java:

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;
     }

     @Override
     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");

     user1.setUsername("JCG");
     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");

     user1.setPassword("JavaCodeGeeks!");
     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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close