TIL: Java Encapsulation

One of the things that has puzzled me the most since I started looking into Java is why everything has these getter and setter methods. Coming from python and javascript it made 0 sense to me why we weren’t just accessing data by its name and instead going through what seemed like an unnecessary step. Today I learned that there’s actually a word for it: encapsulation.

Encapsulation isn’t just a concept, but it’s an overall goal of OOP. The idea being that we need to protect the data that exists in our classes. We don’t want anyone to be able to go in and just start blowing up our data however they feel like.

That’s where the concept of getters and setters come into play. When we create our data in our class, we mark it all as private so that it will only be accessible from within the class. In order for the outside to be able to interact with it, we create getter and setter methods which act as a proxy for accessing this data.

This allows us the ability to run any additional code that we want/need to at the time of reassignment or retrieval (such as logging the requests somewhere).

So the name encapsulation comes from the fact that we’re “encapsulating” our data to a specific class, and limiting access to that data as we see fit.

Now for a simple example. I’ve created two different classes: chicken and dinner. Chicken has a bunch of variables, and dinner creates an instance of chicken. This example shows that it’s not possible for dinner to directly interface with the variables inside of chicken, but rather must use the getters and setters to interface with the data.

Chicken.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
public class Chicken {
   private int age;
   private String name;
   private int weight;

   public int getAge() {
       return age;
   }

   public void setAge(int age) {
       this.age = age;
   }

   public String getName() {
       return name;
   }

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

   public int getWeight() {
       return weight;
   }

   public void setWeight(int weight) {
       this.weight = weight;
   }
}

Dinner.java

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class Dinner {
   public static void main(String[] args) {
       Chicken charles = new Chicken();
       // You can't access the variable directly because it's been marked as private due to encapsulation
       // Trying to access directly will fail!
       // charles.age = 12;

       // Need to use the setter instead!
       charles.setAge(12);
       charles.setName("Charles");
       charles.setWeight(34);

       // Just like with setting, you have to use the getter in order to access the data back out
       System.out.println(charles.getAge());
       System.out.println(charles.getName());
       System.out.println(charles.getWeight());

   }
}

💚