# Encapsulation in Java

In 
Published 2022-12-23

# Encapsulation in Java - theory

In Java OPP (Object-Oriented Programming) we speak about 4 main concepts:

This tutorial explains to you the concept of encapsulation. For a good understanding of the concept you will have an example.

When we speak about Java encapsulation, we speak about hiding data. We don't know how the attributes of a class are defined and used, but we still can modify and see some variables. This is done using getters & setters in Java.

# Encapsulation in Java - example

Here is an example:

Car.java
public class Car {
 
    private String color; 
    private int age;
    private String type;
     
    private String owner;
     
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getType() {
        return type;
    }
    public void setType(String type) {
        this.type = type;
    }
}
ApplicationMain.java
public class ApplicationMain {

    public static void main(String [] args) {
        Car car = new Car();
        car.setColor("green");
        car.setAge(4);
        car.setType("Peugeot");
 
        System.out.println("This car is "+car.getColor()+".");
        System.out.println("This car has "+car.getAge()+" years old.");
        System.out.println("This car is a "+car.getType()+".");
    }
}

When we run the 'main' class we have the following result:

java ApplicationMain

This car is green.
This car has 4 years old.
This car is a Peugeot.

As you can see in the main class you cannot set directly the variable. The variable could be seen/modified using some methods. For doing this, you have to create "getters" and/or "setters" and to define the class variable as "private".

# Access modifiers

Somehow related to the encapsulation we have the Java access modifiers. In Java, the access modifiers are used to set the accessibility of variables, methods (including the setter & getter methods), classes, interfaces, constructors.

Here we have the list of access modifiers and their impact:

Access modifier within class within package outside package (subclass only) outside package (global)
private V X X X
default (no access modifier) V V X X
public V V V V
protected V V V X