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
|
|
Dinner.java
|
|
💚