Understanding Encapsulation in OOP made Easy

In this article, let's understand the basics of encapsulation and why this is an important characteristic of any Object Oriented Language

Introduction

Encapsulation is one of the key characteristics of an Object Oriented Programming Language. The other characteristics are Abstraction, Inheritance and Polymorphism. Any Object Oriented Programming Language must have features that support these characteristics.

What is Encapsulation?

Encapsulation can be simply stated as “hiding entities which are not required for the context”. In other words, it means to deny access to those features or contents which aren’t needed for the other components to get hold of.

The client or the requesting component need not know all the details of the component it is requesting, it just needs to be informed of only things it requires to get things done.

Another explanation for Encapsulation is that to wrap all the information and functionality which represent a responsibility together under a logical structure.

This logical structure provides the necessary housing for all the elements under it from any unwanted access, thereby acting as a barrier for the outside.

Why is Encapsulation important in OOP?

Any structure which complies to Encapsulation does the following –

  1. Wraps up all things which share a common responsibility
  2. Hides these things from any unwanted access

The logical structure which provides the housing for all these entities is called a Class, and any component which needs to access these entities wrapped within a Class by means of a physical reference called an Object.

A Class provides a logical structure and a lock, while the object for a class is the key to its access.

Example of Encapsulation in C#

In the previous example of a MusicPlayer class, the information (represented by the variables) and the functionality (represented by the methods) share a common responsibility: simulating the work of a Music Player.

Hence it makes sense to wrap all these items together by a logical structure aka a class by the name MusicPlayer.

public class MusicPlayer
{
    private List<string> songsLibrary;
    private List<string> playQueue;
    bool isPlaying;

    public MusicPlayer(ILibraryService service)
    {
        // initialization functionality
    }

    public void pause()
    {
        // functionality
    }

    public string resume()
    {
        // functionality
    }

    public void play(string songName)
    {
        // functionality
    }

    public IEnumerable<string> search(string keyword)
    {
        // functionality
    }

    public void stop()
    {
        // functionality
    }
}

This class MusicPlayer creates a logical grouping for all functionalities and related information under a single entity called class MusicPlayer which can be accessed from the outside when needed by means of an instance of this class.

An instance for this class is created as below –

MusicPlayer musicPlayer = new MusicPlayer();

Whenever we use a new keyword followed by the class type, we’re literally creating a “physical copy” of this otherwise logical entity in the memory and accessing the functionality and data out of it.

An Object is a physical copy of the Class which is a logical structure.

Also, observe the keywords which prefix the methods and fields inside the class: public, private.

These are called “Access Modifiers” which specify the accessibility of a particular field or method inside a class from an outside world perspective.

Generally speaking, there are four kinds of access modifiers which define whether a field or a method is deemed to be accessed from out of class or not; if accessible, how far the accessibility can be.

What are the different types of access scopes?

The scope of accessibility can be – local, referential or inherited. Based on these accessibility scopes, there are four access modifiers in C# language for example. Every language has its own nomenclature, but the core idea remains the same.

  1. public – accessible from outside of a class, package or a subclass (local, referential and inherited).
  2. private – accessible from only within the class where the field or method is specified and nowhere else (local only).
  3. protected – accessible from within the class and within the derivative subclasses only (local, inherited only).
  4. default / no modifier – the default access specifier provides access from within class only (local only)
Access ModifierAccessibility Scope
Publiclocal, referential and inherited
Privatelocal
Protectedlocal, inherited
Defaultlocal
access modifiers in C# language and their accessibility levels

Conclusion – Key Takeaways

I hope this article gave you a clear understanding of what is meant by encapsulation in oop and why it is useful.

The following are the key takeaways you need to remember –

  1. Encapsulation provides a logical grouping for the data and functionality which serve a single responsibility.
  2. It also provides information hiding from unwanted access.
  3. This logical grouping is done by a class and is accessed by an object.
  4. The access modifiers provide necessary locks over a class contents from outside access in public, private or protected terms

abstraction and encapsulation difference – how is abstraction different from encapsulation

AbstractionEncapsulation
Abstraction specifies and exposes only what others must know about a componentEncapsulation provides information hiding from unwanted access
The level of abstraction can be on the data or the functionality providedIt provides a logical grouping for the data and functionality which serve a single responsibility. It
Other components interact to this component only via its abstractionA encapsulated grouping is done by a class and is accessed by an object
access modifiers provide necessary locks over a class contents from outside access in public, private or protected termsaccess modifiers provide necessary locks over a class contents from outside access in public, private or protected terms

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *