Java Encapsulation Tutorial

In this section, we will learn what the Encapsulation is and how to use it in Java.

What is encapsulation in Java? (Encapsulation Definition)

The idea of encapsulation in Java means to hide those data members from objects that are created from that class and limit the access to these member variables only via the public methods of that class.

How to implement encapsulation in Java?

Create a class named `Employee` that has this body:

public class Employee {
    private String name;
    private String lastName;
    private int id;

    public Employee(){}
    public Employee(int id, String name, String lastName){
        this.id = id;
        this.name = name;
        this.lastName = lastName;
    }
    public String getName() {
        return name;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

Now create another class named `Simple` that has this body:

public class Simple {

    public static void main(String[] args) {
        Employee john = new Employee(100, "John", "De");
        System.out.println(john.getId());
        System.out.println(john.getName());
        john.setLastName("Doe");
        System.out.println(john.getLastName());
    }
}

Output:

10

John

Doe

The `Employee` class has 3 member variables and all are set to `private`. Setting the access specifiers of these variable to `private` means we’ve encapsulated (hide) these variables from direct external access. Next, we’ve created a few public methods to get and set the value of these private members.

So now if we create an object from this class, it has only the access to the public methods of the class and the private members are hidden from the object.

This is an example of encapsulation in Java.

Why encapsulation in Java:

  • Encapsulations help to control the access to attributes and methods of a class.
  • Brings flexibility: which means changes can be made to part of a class without affecting other parts.
  • And above all, it increases the security of data in a program.

 

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies