What is Encapsulation in OOPS?

by kevin| Views: 34156

What do you mean by Encapsulation in Object Oriented Programming?

Why we need Encapsulation and what is its importance?

How Encapsulation is different than information hiding?

Encapsulation VS Abstraction? What is the difference between Encapsulation and Abstraction?

Tags:  OOPS Interview

Answers (1)
Rick Said..

Encapsulation is the process of keeping state and behavior of the object in a single unit and exposing public methods to act upon the state means hiding internal data of the object from the outside world.

Programming languages like C and Pascal can both produce object-like constructs. In C, this feature is called a struct; in Pascal, it is referred to as a record. Both are user-defined data types. In both languages, a function can operate on more than one data type. The inverse is also true: more than one function can operate on a single data type. The data is fully exposed and vulnerable to the whims of anyone who has an instance of the type because these languages do not explicitly tie together data and the functions that operate on that data.

In contrast, object-oriented programming is based on encapsulation. When an object’s state and behavior are kept together, they are encapsulated. That is, the data that represents the state of the object and the methods (Functions and Subs) that manipulate that data are stored together as a cohesive unit.

Encapsulation is often referred to as information hiding. But although the two terms are often used interchangeably, information hiding is really the result of encapsulation, not a synonym for it. They are distinct concepts. Encapsulation makes it possible to separate an object’s implementation from its behavior—to restrict access to its internal data. This restriction allows certain details of an object’s behavior to be hidden. It allows us to create a “black box” and protects an object’s internal state from corruption by its clients.

Encapsulation is also frequently confused with abstraction. Though the two concepts are closely related, they represent different ideas. Abstraction is a process. It is the act of identifying the relevant qualities and behaviors an object should possess. Encapsulation is the mechanism by which the abstraction is implemented. It is the result. The radio, for instance, is an object that encapsulates many technologies that might not be understood clearly by most people who benefit from it.

In C++, JAVA, C#, Visual Basic .NET, the construct used to define an abstraction is called a class. The terms class and object are often used interchangeably, but an object is actually an instance of a class. See: What is the relation between Classes and Objects?. A component is a collection of one or more object definitions, like a class library in a DLL.

Register or Login to Post Your Opinion/Answer