Encapsulation in Java

Encapsulation in Java

Encapsulation in Java

Before OOPs concept was introduced, data was insecure and used to travel over the network without any access restriction. Anyone was able to access and modify the data like in case of “C” programming language. Today, data is an important asset for any individual, group or company. So you need to protect your information from unauthorized  access and modification. And you can simply do this with “Encapsulation”.

In this tutorial, we will discuss about “Encapsulation” in java. It’s advantages and important things to remember before we can implement it in our program.


Encapsulation in Java
Encapsulation in Java



What is Encapsulation


Encapsulation is used to implement abstraction in Object Oriented Programming. Encapsulation allows you to protect your information and add some access restrictions. Now you will be able to decide what should be visible to the public and what should be private.

Some important things to remember

  1. Encapsulation ensures that your information is secure by applying access restrictions on fields and methods of your class.
  2. As per convention, you should make your all fields private.
  3. You should create getter and setter methods in order to set and access private fields of your class.
  4. With the help of getter and setter methods, you will be able to set access levels like – you only want read operation on your class or read and write both.
  5. You can also protect you application from unwanted data insertion by applying some validation inside setter method of your class variable.
  6. You can also prepare data of you choice before inserting it into instance variable like date format, number format etc inside setter methods.

Let’s understand encapsulation with real scenario

You have a task in which you need to create a class which is PizzaDetails. In this class, you need to add fields like order id, pizza type, pizza name, extra cheese, size. But you need to prepare your class as per below check list.

  1. Your information should be private. No other resource should be able to modify pizza details directly.
  2. Pizza size will be provided as input 1,2,3. You need to prepare data as 1 for SMALL, 2 for MEDIUM, 3 for LARGE.
  3. You need to provide a way so that other resource can set and get pizza details publicly.
  4. You need to create a method which will provide pizza details for print purpose.

So let’s get started.

class PizzaDetails {

      private String orderId;
      private String pizzaType;
      private String pizzaName;
      private boolean extraCheese;
      private String pizzaSize;

      public String getOrderId() {
        return orderId;
      }
      public void setOrderId(String orderId) {
        this.orderId = orderId;
      }

      public String getPizzaType() {
        return pizzaType;
      }
      public void setPizzaType(String pizzaType) {
        this.pizzaType = pizzaType;
      }

      public String getPizzaName() {
        return pizzaName;
      }
      public void setPizzaName(String pizzaName) {
        this.pizzaName = pizzaName;
      }

      public boolean isExtraCheese() {
        return extraCheese;
      }
      public void setExtraCheese(boolean extraCheese) {
        this.extraCheese = extraCheese;
      }

      public String getPizzaSize() { 
        return pizzaSize;
      }
      public void setPizzaSize(String pizzaSize) {
        if(pizzaSize.equals("1")) {
          this.pizzaSize = "SMALL"; 
        } else if(pizzaSize.equals("2")) {
          this.pizzaSize = "MEDIUM";
        } else if(pizzaSize.equals("3")) {
          this.pizzaSize = "LARGE";
        }
      }

      public String getPizzaDetails() {
          return this.getPizzaName() + ", " + this.getPizzaType() + ", " + this.getPizzaSize();
      }

      public static void main(String arg[]) {

          PizzaDetails pd = new PizzaDetails();
          pd.setOrderId("2033");
          pd.setPizzaType("cheese-burst");
          pd.setPizzaName("Margherita");
          pd.setExtraCheese(true);
          pd.setPizzaSize("2");

          System.out.println(pd.getPizzaDetails()); // Margherita, cheese-burst, MEDIUM
      }
      
}

Let’s understand the above example. This is perfect example to understand the concept of encapsulation and how we are applying it in our day to day projects. Let’s go through to our check list one by one.
  1. Your information should be private. No other resource should be able to modify pizza details directly.

    We did it by making our all fields private. So no resource will be able to modify our variables directly.
  2. Pizza size will be provided as input 1,2,3. You need to prepare data as 1 for SMALL, 2 for MEDIUM, 3 for LARGE.

    We added a logic inside our setter method. Where we are checking string value with equals method (equals method check the equality of two strings and returns true/false based). If value is 1 then SMALL will be the value and so on.
  3. You need to provide a way so that other resource can set and get pizza details publicly.

    We created public getter and setter methods for each instance variable so that other system will be able to add pizza details.
  4. You need to create a method which will provide pizza details for print purpose.

    We created a separate method for that purpose which getPizzaDetails(), which will return a string containing pizza information for print purpose.

One thought on “Encapsulation in Java”

Leave a Reply

Your email address will not be published. Required fields are marked *