Encapsulation With Example And Program In JAVA

Encapsulation is one of the four key concepts in OOPS (Object Oriented Programming) namely Inheritance, Encapsulation, Abstraction and Polymorphism. Following definition helps you to understand the concept of encapsulation:

  • Encapsulation is a process of hiding the data from the users or in other words we can say it protects the code by preventing access from the outside class.
  • We can say wrapping up of data member and member functions together into a single unit (i.e. Class) is called Encapsulation.
  • To achieve abstraction in JAVA we set data fields as private which means now no outside class can access it. However to allow outside class to read and write the data on those data fields we create public getter and setter methods.
  • Encapsulation means hiding the internal details of an object i.e. how an object does something. It prevents clients from seeing its inside view, where the behavior of the abstraction is implemented.
  • Encapsulation is also known as Data Hiding

Important Note: Encapsulation is achieved by making the fields private and using setter & getter public methods to set and get data in it.


Encapsulation Explanation With Example In JAVA:

Now we will explain the concept of Encapsulation with example.

Example 1: In the below example, we will set two fields as private name and email in class UserDetails. So these fields can only be access within this class and no outside class can access it. Also here we will create public methods getter (Ex. getName()) and setter (Ex. setName()) to read and write data on those fields from outside class. By doing this we are hiding the fields and its implementation from outside class. This whole process is known as Encapsulation which is also called as Data Hiding.

Step 1: Create a class UserDetails, two private fields name and Email. Also create public getter and setter methods.

//Save as UserDetails.java

public class UserDetails
{

    private String name;
    private String email;

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public String getEmail()
    {
        return email;
    }

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


}

Step 2: Create a new class User. Here create a object for UserDetails in main method. On object call method setName() and setEmail() to write values and then call method getName() and getEmail() to read values.

//Save as User.java

public class User {

    public static void main(String[] args) {
        
        UserDetails userDetails = new UserDetails();
        
        userDetails.setName("AbiAndroid");
        userDetails.setEmail("info@abhiandroid.com");
        
        System.out.println("Name: "+userDetails.getName());
        System.out.println("Email: "+userDetails.getEmail());

    }

}

Output:

Name: AbiAndroid
Email: info@abhiandroid.com

Important Note: The public setName(), setEmail(), getEmail() and getName() methods are the access points of the instance variables of the UserDetails class. Normally, these methods are referred as getters and setters in JAVA. Therefore any outside class that wants to access those variables should access them through these getters and setters only.


Real Life Encapsulation Example in Java:

Lets try to understand the concept of Encapsulation with one more example. Here we will use FruitDetails class which has all related data fields like name, price and color.

Step 1: Create class FruitDetails and create three private fields for name, price and color. Also create constructor which will be used for initializing values of FruitDetails object that we will create other class.

After that create Getter and Setter for all fields.

//Save as FruitDetails.java

public class FruitDetails
{
    //Data members of class FruitDetails
    private String name;
    private String price;
    private String color; 

    //declaration of constructor
    public FruitDetails(String name, String price, String color)
    {
        this.name = name;
        this.price = price;
        this.color = color; 
    }
    
    //Declaring Setter for all fields
    public void setName(String name) {
        this.name = name;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public void setColor(String color) {
        this.color = color;
    }

    //Declaring Getter for all fields
    public String getName()
    {
        return name;
    }

    public String getPrice()
    {
        return price;
    }

    public String getColor()
    {
        return color;
    }

}

Step 2: Create another class Fruit and here create object for FruitDetails class. Here fill the details of Fruit suppose apple in constructor. After that use getter to get the value and print it. Then change the initialized value using setter and again use getter to print the updated value.

//Save as Fruit.java

public class Fruit {

    public static void main(String[] args) {
        
        FruitDetails apple = new FruitDetails("Apple","$3","Red"); //Using constructor to inititialize
        
        //Using getter to the value
        System.out.println("Name: "+ apple.getName()+" Price: "+apple.getPrice()+" Color: "+apple.getColor());
        
        //Lets update the price and color using setter
        apple.setColor("Green");
        apple.setPrice("$7");
        
        System.out.println("Values of Apple after updation");
        
        //Using getter to get the value
        System.out.println("Name: "+ apple.getName()+" Price: "+apple.getPrice()+" Color: "+apple.getColor());
    }

}

Output:

Name: Apple Price: $3 Color: Red
Values of Apple after updation
Name: Apple Price: $7 Color: Green

Importance Of Encapsulation:

  • The fields of a class can be made read-only or write-only.
  • Class can have total control over what is store in its fields.
  • The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.
  • The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code.
  • Encapsulation gives maintainability, flexibility and extensibility to our code.
  • Encapsulation in Java makes unit testing easy.
  • Encapsulation allows you to change one part of code without affecting other part of code.

Important Points To Remember:

  • “Encapsulation is accomplished by using Class i.e. keeping data and methods into a single unit” .
  • Encapsulation is a technique used to protect the information in an object from the other object.
  • Encapsulation is said to be providing “access control” through which we can control which parts of the program can access the members of any class and thus prevent misuse. Various access controls are public, private and protected.

Difference Between Abstraction And Encapsulation :-

Abstraction Encapsulation
1. In java, Abstraction solves the problem in the design level. 1. In java, Encapsulation solves the problem of the implementation level.
2. Abstraction is used for hiding the unwanted data and gives relevant data. 2. Encapsulation means hiding the code and data into a single unit to protect the data from outside world.
3. Abstraction lets you focus on what the object does instead of how it does it. 3. Encapsulation means hiding the internal details or mechanics of how an object does something.
4. Abstraction is an Outer layout, used in terms of design. For Example: Outer Look of a Mobile Phone, like it has a keypad buttons to dial a number and display screen. 4. Encapsulation is an Inner layout, used in terms of implementation. For Example: Inner Implementation detail’s of a Mobile Phone, how’s Display Screen and keypad button are connect with each other using circuits.

Real World Example To Better Understand Abstraction And Encapsulation Difference:

You have a Mobile Phone, you can dial a number using keypad buttons. Even you don’t know how these are working internally. This is achieved in JAVA using Abstraction. But how the Mobile Phone internally working? How keypad buttons are connected with internal circuit? This is achieved using Encapsulation.

You can read Abstraction Tutorial for more details.

Leave a Reply

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