Encapsulation in Java

Encapsulation is one of the fundamental principles of Object-Oriented Programming (OOP) in Java. It is a technique of hiding the internal details of an object from the outside world and exposing only the necessary information. In this tutorial, we will discuss what encapsulation is in Java and how to implement it with examples.

Encapsulation in Java

Encapsulation is the practice of bundling data and methods (functions) together into a single unit, which is called a class. The data and methods inside the class are then kept private and can only be accessed by other methods inside the same class. This helps to protect the data from external interference and ensures data integrity.

To achieve encapsulation in Java, we use access modifiers. There are four access modifiers in Java – private, public, protected, and default (also known as package-private). The private access modifier is used to make the data and methods inside a class only accessible from within the same class.

Let’s look at an example to see how encapsulation works in Java.

public class Person {
    private String name;
    private int age;
    
    public void setName(String name) {
        this.name = name;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
}

In this example, we have defined a class called “Person” that has two private data members – “name” and “age” – and four public methods – “setName()”, “setAge()”, “getName()”, and “getAge()”. The “setName()” and “setAge()” methods are used to set the values of the “name” and “age” variables, while the “getName()” and “getAge()” methods are used to get the values of these variables.

Notice that the data members are private, which means they can only be accessed from within the same class. However, the methods that access these data members are public, which means they can be accessed from outside the class.

Let’s look at an example of how to use the “Person” class:

public class Main {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("John");
        person.setAge(25);
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());
    }
}

In this example, we have created an object of the “Person” class and set its name and age using the “setName()” and “setAge()” methods. We then print out the name and age using the “getName()” and “getAge()” methods. Notice that we are able to access the data members of the “Person” class using its public methods, but we cannot access them directly.

Also, see the example code JavaExamples_NoteArena in our GitHub repository. See complete examples in our GitHub repositories.

Follow us on social media
Follow Author