Skip to content

OOP Encapsulation Introduction#

What Is The Encapsulation In OOP?#

  • Encapsulation in Java is a mechanism to wrap up variables(data) and methods(code) together as a single unit. It is the process of hiding information details and protecting data and behavior of the object.
  • In Java, a class is an example of encapsulation in that it consists of data and methods that have been bundled into a single unit (wrapping) and restricted accesses from other classes by access modifiers (hiding information).
  • To achieve encapsulation in Java, a class has to set attributes (variables) as private and provide public setter and getter methods to modify and view these attributes. See example below.

Encapsulation Example#

  • Create an encapsulation class with name Motorcycle.
Motorcycle.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class Motorcycle {

    private String name;
    private String color;
    private String model;

    public String getName() {  
    return name;  
    }  

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

    public String getColor() {  
            return color;  
    }  

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

    public String getModel() {  
            return model;  
    }  

    public void setModel(String model) {  
            this.model = model;  
    }

}
  • Test the class Motorcycle.
Main.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Main {

    public static void main(String[] args) {

        Motorcycle motorcycle = new Motorcycle();
        motorcycle.setName("Wave");
        motorcycle.setColor("Black");
        motorcycle.setModel("Wave Alpha");

        System.out.println(motorcycle.getName());
        System.out.println(motorcycle.getColor());
        System.out.println(motorcycle.getModel());

    }

}
1
2
3
4
5
//result

Wave
Black
Wave Alpha

See Also#