Let’s Do It PL
Published in

Let’s Do It PL

Let’s Do It PL

What is “Encapsulation” and What are the Benefits of It?

Object-Oriented Programming is a very beneficial programming type for creating objects that have data and functions. We usually come across the OOP term and its principles in languages like C#, JavaScript, Java, and many others. In this article, we will touch on one of its 4 principles using Java: Encapsulation.

Before explaining what Encapsulation is, let’s look at its definition. Encapsulation means enclosing something in a capsule for keeping together whatever we put inside. A capsule does not let it's contents out so ingredients can stay together. For example, medicine is some mixture encapsulated inside a pill that we can use when we need it. With that pill, the ingredients of the medicine are the same as the first time it was mixed and the contents inside cannot be changed from the outside.

Let’s change some words there and try to look from the developers’ scope. If we put “Objects” instead of “medicine” and “Classes” instead of the “pill” then our ingredients become “Methods” and “Variables” inside that class. Here comes the main sentence for our principle:

An object should encapsulate its methods and variables inside a class and should use them when needed.

Encapsulation simply aims to keep data and methods together to avoid repetition and create correct and logical connections between objects. Also, it lets the developer put some rules on the object creating and using. But how can we do that? There are 4 keywords for this simple but important action: Public, Private, Default, Protected. We call them “Access Modifiers” and any data structure declaration starts with them.

1-Public

The “public” keyword is very common and we can see it in any programming language. As we can deduce from its meaning, the “public” keyword allows usage wherever, even outside of where it is declared. Let’s suppose we have a method named run() and it is public. Whenever an object is created, which has run() method inside, we can call that method without any error. It is a pretty ordinary situation if we do not use any other access modifier.

2-Private

The “private” keyword does the exact opposite of the “public” keyword. It does not allow any usage outside of class that is declared. If we change the public method run() to private we cannot use it wherever the object is created. If we try to call it, the compiler throws an error immediately with “run() has private access” sentence.

3-Default

The “default” access modifier has no keyword. If we don’t write public, private, or protected that means that the data structure has a default access modifier. This access modifier is also restricting some access but not as much as private. If a data structure is a default, it can be used in the same package but it is not allowed to be used in other packages.

4-Protected

For explaining the “protected” keyword, we have to briefly mention another OOP principle, Inheritance. Inheritance allows a parent-child relationship between objects. With that principle, classes can inherit some methods and variables from other classes and use them. We call “subclass” which inherits some data from other classes, and “superclass” which is inherited.

Difference between “default” and “protected” steps in here. The default access modifier doesn’t allow for usage outside of its package but protected data structures can be used in subclasses that are outside of its package.

We call using access modifiers “Data Hiding”. The question becomes: Does hiding something mean that we won’t use it again? No, right? People hide something to use later but only when needed. Like how we use medicine when we get sick. After we hide our data, we can create some methods to change these data or use them later. We call these methods “Getter and Setter Methods”.

Getter and Setter Methods

These methods are not special methods like constructors and they do not have to be written. Getter and Setter methods are simply just globally accepted and used methods and they have a rule for naming. We put ‘get’ and ‘variable name’ for the naming of a Getter Method, and we do the same thing with ‘set’ for a Setter method. It is not necessary for code works but it makes your code cleaner and more understandable. Let’s explain with an example:

public class Cat {
private String name;
private int age;
final int numOfLegs = 4;

public String getName() {
return name;
}

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

public int getAge() {
return age;
}

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

We have a class named Cat and it has private variables. If we want to change the value of the ‘name’ variable we can use the setName() method or we can use that value with the getName() method because they are public, unlike the ‘name’ variable.

Cat cat = new Cat();
cat.setName("Garfield");
System.out.println(cat.getName());

These methods do not do anything special, right? Just a normal declaration and returning that value. The thing is they do these little actions in methods and methods can be manipulated by developers.

Suppose we wrote this code for a ‘Cat Beauty Contest’ and they only allow 0–1 years old cats to contest. If we update ‘age’ directly with the ‘= operator, we may cause unintended side effects somewhere else in our code. Also, we most probably have to deal with many if-else blocks. If we want to avoid this issue by using a Setter method, we should add a condition once to the Setter Method of age:

public void setAge(int age) {
if (age > 0 && age < 1) {
throw new IllegalArgumentException();
}
this.age = age;
}

Read-Only and Write-Only Classes

Getter and Setter methods also let us create “Read-Only Class” and “Write-Only Class”. Like we said before, Getter and Setter methods are not obliged to be part of that class. We need Setter methods to set a new value to a private variable but what if we do not have any Setter methods and only Getter methods? It means, we can only use that variable but we cannot change it from outside of that class which makes that class Read-Only.

//Read-Only Cat Class
public class Cat {
private String name;
private int age;

public String getName() {
return name;
}

public int getAge() {
return age;
}
}

Just like the Read-Only class, if we do not use any Getter methods and only use Setter methods, it makes that class Write-Only. With that, we created a class that has changeable but non-usable variables.

//Write-Only Cat Class
public class Cat {
private String name;
private int age;

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

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

Achievements and Conclusion

We learned what Encapsulation is and how it can be used but what did we achieve by that?

  1. We hid our data from unintended changes,
  2. We created a class that has control over what is stored inside its fields,
  3. We created Read-Only and Write-Only classes,
  4. We reduced human-based errors,
  5. We wrote our code in a cleaner and more understandable way,
  6. We made our application simpler.

Encapsulation is one of the big pillars that OOP is built on. By using OOP, we aim to create more functional, shorter, cleaner, easier to maintain, more secure, and reusable codes. Encapsulation almost helps all of these aims of OOP and therefore it has been very important and necessary to learn. Understanding it is a key to success in Object-Oriented Programming.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store