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.

public Class OurNewObject(){

//variable to store some string
private String randomString;

//lets outside forces set the string
public void setRandomString(String text){
this.setRandomString = text;

//returns the string
public String getRandomString(){
return this.randomString;

public OurNewObject(){



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…

.... main(String[] args){

OurNewObject Poop = new OurNewObject();

//Doesn't work

Poop.setRandomString("Bubble bubble");


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.

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
Leave a Reply
You May Also Like

5 YouTube SEO Tips for 2015

Ranking on YouTube can be difficult, especially without the right approach. A…

Hack This Site: Realistic 2 Solution

This is a simple step-by-step solution guide for Realistic 2 on Hack…

A Basic Overview of PHP OOP (Object-Oriented Programming)

OOP consists of programming languages that manipulate Objects. They tend to use… Review (CPA Network)

Adludum is a new CPA network that is destined for some pretty…