What Is Encapsulation in Java?

217
0
SHARE

In Java, and generally in Object-oriented programming, there’s this magical thing called “Encapsulation”.

Encapsulation brings variables and methods together as a single thing. This way the variables within (for ease’ sake) an object can only be accessed by operating the object.

Let’s say we’ve got a Car and we want it to go faster. We need to operate the Object by pushing on the gas pedal. If we could access the driving speed directly we could just change the speed from 0 to 100 in a matter of milliseconds. Whip-lash court cases galore .etc would taint existence.

Example of Encapsulation in Java

We start by making an object. OurNewObject. We add a randomString variable, set it to private so it’s not accessible by outside forces.

There also some setters and getters. Basically, so the outside forces can adjust the variable. But only on our terms.

If we then try to access the randomString variable from anywhere else in our program we’re gonna run into problems…

Why would we use Encapsulation?

If you wanted to make your content read-only or write-only then you have the option to do so.

Related:  How to Use Java's Scanner to Read Text Files

You can also decide what can be input or output from your class. Say you want to store passwords, you can make it so the password is only ever stored encrypted and never returned to the user that might be requesting it.

How Do You Use Encapsulation?

You need a few vital things.

  • Private variables in a Class
  • Getters and setters (if you want) to modify these private variables