Encapsulation in Java

Thanoshan MV
4 min readMay 1, 2020

Encapsulation is a process of wrapping code and data together into a single unit.

It’s just like a capsule that contains a mix of several medicines, and is a technique that helps keep instance variables protected.

This can be achieved by using private access modifiers. They can’t be accessed by anyone outside the class. In order to access private states safely, we have to provide public getter and setter methods. (In Java, these methods should follow JavaBeans naming standards.)

Let’s say there is a record shop that sells music albums of different artists and a stock keeper who manages them.

Figure 1: Class diagram without encapsulation

If you look at figure 4, the StockKeeper class can access the Album class’s states directly as Album class’s states are set to public.

What if the stock keeper creates an album and sets states to negative values? This can be done intentionally or unintentionally by a stock keeper.

To illustrate, let’s see a sample Java program that explains the above diagram and statement.

Album class:

public class Album {
public String name;
public String artist;
public double price;
public int numberOfCopies;
public void sellCopies(){
if(numberOfCopies > 0){
numberOfCopies--;
System.out.println("One album has sold!");
}
else{
System.out.println("No more albums available!");
}
}
public void orderCopies(int num){
numberOfCopies += num;
}
}

StockKeeper class:

public class StockKeeper {
public String name;
public StockKeeper(String name){
this.name = name;
}
public void manageAlbum(Album album, String name, String artist, double price, int numberOfCopies){
/*
Defining states and behaviors for album
*/
album.name = name;
album.artist = artist;
album.price = price;
album.numberOfCopies = numberOfCopies;

/*
Printing album details
*/
System.out.println("Album managed by :"+ this.name);
System.out.println("Album details::::::::::");
System.out.println("Album name : " + album.name);
System.out.println("Album artist : " + album.artist);
System.out.println("Album price : " + album.price);
System.out.println("Album number of copies : " + album.numberOfCopies);
}
}

Main class:

public class Main {
public static void main(String[] args) {
StockKeeper johnDoe = new StockKeeper("John Doe");
/*
Stock keeper creates album and assigns negative values for price and number of copies available
*/
johnDoe.manageAlbum(new Album(), "Slippery When Wet", "Bon Jovi", -1000.00, -50);
}
}

Output:

Album managed by :John Doe
Album details::::::::::
Album name : Slippery When Wet
Album artist : Bon Jovi
Album price : -1000.0
Album number of copies : -50

Album’s price and number of copies can’t be in negative values. How can we avoid this situation? This is where we use encapsulation.

Figure 2: Class diagram with encapsulation

In this scenario, we can block stock keeper to assign negative values. If he attempts to assign negative values for album’s price and number of copies, we’ll assign them as 0.0 and 0.

Album class:

public class Album {
private String name;
private String artist;
private double price;
private int numberOfCopies;
public void sellCopies(){
if(numberOfCopies > 0){
numberOfCopies--;
System.out.println("One album has sold!");
}
else{
System.out.println("No more albums available!");
}
}
public void orderCopies(int num){
numberOfCopies += num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
if(price > 0) {
this.price = price;
}
else {
this.price = 0.0;
}
}

public int getNumberOfCopies() {
return numberOfCopies;
}
public void setNumberOfCopies(int numberOfCopies) {
if(numberOfCopies > 0) {
this.numberOfCopies = numberOfCopies;
}
else {
this.numberOfCopies = 0;
}
}

}

StockKeeper class:

public class StockKeeper {
private String name;
StockKeeper(String name){
setName(name);
}
public void manageAlbum(Album album, String name, String artist, double price, int numberOfCopies){
/*
Defining states and behaviors for album
*/
album.setName(name);
album.setArtist(artist);
album.setPrice(price);
album.setNumberOfCopies(numberOfCopies);
/*
Printing album details
*/
System.out.println("Album managed by :"+ getName());
System.out.println("Album details::::::::::");
System.out.println("Album name : " + album.getName());
System.out.println("Album artist : " + album.getArtist());
System.out.println("Album price : " + album.getPrice());
System.out.println("Album number of copies : " + album.getNumberOfCopies());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Main class:

public class Main {
public static void main(String[] args) {
StockKeeper johnDoe = new StockKeeper("John Doe");
/*
Stock keeper creates album and assigns negative values for price and number of copies available
*/
johnDoe.manageAlbum(new Album(), "Slippery When Wet", "Bon Jovi", -1000.00, -50);
}
}

Output:

Album managed by :John Doe
Album details::::::::::
Album name : Slippery When Wet
Album artist : Bon Jovi
Album price : 0.0
Album number of copies : 0

With encapsulation, we’ve blocked stock keeper to assign negative values (We are having the control over the data).

Advantages of encapsulation in Java

  1. We can make a class read-only or write-only: for a read-only class, we should provide only getter method. For write-only class, we should provide only setter method.
  2. Control over the data: we can control the data by providing logic to setter methods. Just like we restricted stock keeper from assigning negative values in the above example.
  3. Data hiding: other classes can’t access private members of a class directly.

Now we know about encapsulation. If you have any doubts or if you think any other important concepts inside the encapsulation is missed here please feel free to let me know. So that we can improve our article and help others to learn easily.

Thank you for reading.

I’ll meet you on the Inheritance in Java article.

Happy coding!

--

--