Encapsulation in Java with Example



< Previous Next >

OOPS Tutorial



In this article, we will learn what is Encapsulation in Java with real-world examples and source code examples.
Encapsulation refers to combining data and associated methods as a single unit. In this post, we will learn Encapsulation in detail with examples.

1. Intent/Definition 

Encapsulation is the mechanism that binds together code and the data it manipulates and keeps both safes from outside interference and misuse. One way to think about encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily accessed by other code defined outside the wrapper.

In OOP, data and methods operating on that data are combined together to form a single unit, which is referred to as a Class. Read more about Java Class here.

Advantage of Encapsulation:

The main advantage of using encapsulation is to secure the data from other methods. 
For example, when we make fields private then these fields only use within the class, but these data are not accessible outside the class.

2. Encapsulation Real-world Examples

  1. The capsule, it is wrapped with different medicines. In a capsule, all medicine is encapsulated inside capsule.
  2. A Java Class is an example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

3. Implementation with Examples

The process of binding or wrapping the data and the codes that operate on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
For example - if a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class.
Consider below Person class diagram, the id and name parameters should not be accessed directly outside Person class - achieved by private declaration.

Let's create a Person class to demonstrates the use of encapsulation in Java.

Step 1: Create a Person class.
public class Person {

    private double id;
    private String name;

    public Person() {
        // Only Person class can access and assign
        id = Math.random();
        sayHello();
    }

    // This method is protected for giving access within Person class only
    private void sayHello() {
        System.out.println("Hello - " + getId());
    }

    public double getId() {
        return id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
Step 2: Let's test the Encapsulation via a main() method.
public class EncapsulationDemostration {
    public static void main(String[] args) {

        Person p1 = new Person();
        p1.setName("Ramesh");
        /*
         * Note: As id and name are encapsulated in Person class, those cannot be accessed 
         * directly here. Also there is no way to assign id in this
         * class. Try to uncomment below code and you would find compile time error.
         */
        // p1.id = "123";
        // p1.name = "this will give compile time error";
        // p1.sayHello(); // You can't access this method, as it is private to Person

        System.out.println("Person 1 - " + p1.getId() + " : " + p1.getName());
    }
}

4. Difference between Abstraction and Encapsulation

Abstraction and Encapsulation in Java are two important Object-oriented programming concepts and they are completely different from each other.
  • Encapsulation is a process of binding or wrapping the data and the codes that operate on the data into a single entity. This keeps the data safe from outside interface and misuse.
  • Abstraction is the concept of hiding irrelevant details. In other words, make the complex system simple by hiding unnecessary detail from the user.
  • Abstraction is implemented in Java using an interface and abstract class while Encapsulation is implemented using private, package-private, and protected access modifiers.
  • Abstraction solves the problem at the design level. Whereas Encapsulation solves the problem at the implementation level.
Encapsulation: Information hiding.

Comments

Post a Comment