What Is Data Hiding?

In this lesson, you will get familiar with a very important aspect of object-oriented programming called data hiding.

Introduction

In the previous chapter, you got familiar with the concepts of objects and classes.

In OOP, objects and classes are the basic entities. Objects are created using classes. One can observe that classes contain fields and objects are created to manipulate and access these fields. To make this object-oriented system more reliable and error-free, it is good practice to limit access to the class members.

In layman’s terms, data hiding refers to the concept of hiding the inner workings of a class and simply providing a public interface through which the outside world can interact with the class without knowing what’s going on inside.

The purpose is to implement classes in such a way that the instances (objects) of these classes should not allow any unauthorized access or change in the original contents of a class. One class does not need to know anything about the underlying algorithms of another class. However, the two should still be able to communicate.

A Real Life Example

Let’s apply this to a real-world scenario. Take the doctor-patient model. In case of an illness, the patient consults the doctor, after which he or she is prescribed the appropriate medicine.

The patient only knows the process of going to the doctor. In this case, the process of going to the doctor is publicly known and hence it serves as a public interface to access the doctor. The logic and reasoning behind the doctor’s prescription of a certain medicine are unknown to the patient. A patient will not understand the medical details the doctor uses to reach his/her decision on the treatment.

This is a classic example of the patient class interacting with the doctor class without knowing the inner workings of the doctor class.

Get hands-on with 1200+ tech skills courses.