Understanding Encapsulation in Programming
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Introduction
So let us begin by answering the burning question, what is Encapsulation?
To put it simply, encapsulation is the process of surrounding an object with other components in order to conceal its internal details from users.
There are several examples of encapsulation in Java. This concept is easily demonstrated using the class keyword. This keyword enables programmers to create their own custom classes that contain a collection of data and methods used by their programs. These classes can be thought of as belonging to a separate "layer" that only the class's creator has access to.

Multiple Choice
Fill in the blank:
Encapsulation is the process of grouping together data members and functions into a single unit known as _________________.
Types of Encapsulation
Types of Encapsulation?
Let us delve deeper and examine the three types of encapsulation:
1. Member Variable Encapsulation
A class's member variables and methods are encapsulated from outside the class. In theory, this is accomplished by concealing variables and methods within a class. A programmer cannot access or call internal variables or methods unless the code that makes up the class explicitly grants them permission.
2. Class Encapsulation
This type of encapsulation seals the class and prevents users from changing its functionality. For example, if a programmer uses a specific tool to create a class, they are not permitted to edit the source code; only the creator is permitted to change that class. Encapsulated classes are generally inaccessible to users unless they have special permissions.
3. Function Encapsulation
When a programmer calls a function, the function container "encapsulates" that function to hide its internal details. The function can only be called in the same way it was called in the first place. The outcome of calling this function will differ depending on whether or not the programmer calls any other functions during the execution of that program.
Encapsulation’s Relation to Object-Orientated Programming (OOP)
Encapsulation’s Relation to Object-Orientated Programming (OOP)
Encapsulation is a key concept in object-oriented programming. Encapsulation allows a programmer to create and maintain complex programs for the benefit of others rather than relying on the code of another programmer. A programmer could not create a program that can handle complex problems for their customers and other users without the ability to encapsulate and hide code. Therefore the functionality provided by encapsulation makes it a vital component to be knowledgeable on.
Modifiers in Encapsulation
Modifiers in Encapsulation
Modifiers are data that determine whether or not a piece of code should be called. In Java, modifiers such as explicit, abstract, final, and private are available. These can be used to specify how methods and classes access their data. Ideally, these modifiers prevent code from being altered or used in ways that the programmer does not approve of.
Private Fields and Getters
Private Fields and Getters
In Java, encapsulation is most commonly written by making variables private and exposing only the methods that outside code is allowed to use.
This means another class should not directly change the internal data. Instead, it should ask the object to perform an action.
For example, a bank account should not let any code freely change its balance. The BankAccount class can protect that value and decide which changes are valid.

```java
public class BankAccount {
private int balance;
public BankAccount(int startingBalance) {
balance = startingBalance;
}
public int getBalance() {
return balance;
}
public void deposit(int amount) {
if (amount > 0) {
balance += amount;
}
}
}
```
Here, `balance` is hidden from outside classes. Other code can read it through `getBalance()` and change it only through controlled methods like `deposit()`.
Multiple Choice
Which of the following is not a type of encapsulation?
Explaining Encapsulation in an Interview
Explaining Encapsulation in an Interview
So, how do we define encapsulation in simple terms for an interview?
- Encapsulation is the process of constructing a container for private variables and methods.
- It is used to manage variables and functions so that only the creator of the class has access to those hidden values.
- Encapsulation also makes it easier to manage classes and their functions because it prevents users from accidentally changing code or making bad changes without knowing how they will affect the overall program.
Multiple Choice
Which of the following best demonstrates encapsulation for a BankAccount balance in Java?
Why do we Use Encapsulation?
Why do we Use Encapsulation?
Encapsulation is used to properly maintain programs that we write as well as programs written by others. It is a practice to keep code secure and operational rather than allowing it to degrade into a broken mess over time.
Encapsulation is commonly used in the following languages:

Let's examine two popular programming languages, Java and Python, and what encapsulation means in their context.
1. Encapsulation in Java
The following code creates a class called College, with a private variable and method.
public class College {
//Some code here
}
Only the class creator can change its source code or call the hidden private methods. The method can only be used by the creator of the class and would not be accessible to other users. With this in mind, we can see that encapsulation is used for applications that are expected to run for an extended period of time.
2. Encapsulation in Python
The following code creates a class that has the ability to store some private data.
class College:
def output(self, destination=None):
def __init__(self, address):
def print_address(self, destination=None):
These can be completely hidden from other Python code users. The data will only be used by the class's creator and will not be accessible to other users. The output method of the class will print any given value to a printer or display device
True or False?
Encapsulation protects data from outside interference.
Encapsulation vs. Inheritance vs. Abstraction
Encapsulation vs. Inheritance vs. Abstraction
- Encapsulation:
This process hides a class's or object's public or external variables and methods from users. These variables and methods are only available to the class or object's creator. It safeguards data that is specific to each object layer within a system. Users have no access to these private variables or methods.
- Inheritance:
Is a logical concept that extends the concept of encapsulation to multiple objects. In Java, the inherit keyword can be used to add new functionality to a class's base class.
- Abstraction:
Is a method that allows programmers to concentrate their efforts on only one "layer" of their programs at a time. These layers are also known as objects that are separated from one another. Abstraction keeps code manageable and ready for testing before moving on to the next layer of the program.
One Pager Cheat Sheet
One Pager Cheat Sheet
- Encapsulation is a concept in programming where an
objectis surrounded by other components toconcealitsinner detailsfrom users, commonly used inJavawith theclasskeyword. - Encapsulation allows for data members and functions to be grouped together within a
class, creating a secure and organized structure for the object. -
Member Variable, Class, and Function Encapsulation
concealaclass'svariables and methods,sealtheclass, andhidethe internal details of a function, respectively. - Encapsulation is a
key conceptin Object-Orientated Programming (OOP) andenables complex program creationfor the benefit of others. - Modifiers such as
explicit,abstract,finalandprivateinJavacan be used to control access and prevent alteration of code. - Encapsulation and
Abstractionare different practices in coding that are both important for protecting code and data and making it easier to understand. - Encapsulation
creates a containerfor private data, allowing only the class creator to access hidden values and making it easier to manage code without affecting the overall program. - Encapsulation is a practice of keeping code secure and operational by keeping it hidden from other users, and is useful for maintaining programs for an extended period of time in languages such as
JavaandPython. - Encapsulation is a programming technique used to protect data from outside interference, allowing only the code's creator to view and modify it.
- Encapsulation
hidesprivate variables and methods, while Inheritance and Abstraction allow programmers to focus on one layer of their programs at a time.