, ,

Encapsulation is the fundamental concept of OOP. It’s important to know about classes, objects and methods before diving into further details.

Why do we need objects?

I got this from a video on youtube:

Imagine an unsorted pile of a variety of toys and you are asked to find a particular toy, say a toy car from the pile. It would be difficult , though  not impossible,  to find it.

On the contrary, if similar toys are collected together in separate bins and the bins are arranged into shelves, it becomes easy!

Similarly, in programming world, data and methods are put into discrete objects. If the program were a long list of commands, things would become complex.

Class: Class is a blueprint or template which is used to create/ instantiate an object. Classes are created so that we can instantiate similar objects.

It comprises of data/attributes and methods/functions.

Everything in real world can be perceived as an object! Car is an object with it’s data as make, model, year of manufacture, color etc.

Methods are the operations that can be done on the data. For a Car object, methods could be Accelerate, Start, Stop etc.

When you instantiate a class, you create an object.

Multiple objects can be created from a class. Each object will have the methods defined in the class and it’s own copy of data.

Process of combining functionality of object i.e. methods  with data is called encapsulation.

The internal state of one object is hidden from another object i.e. It hides the implementation details and all interaction are to be performed through the object’s methods.


To create a  class Car with data as make, model, color, transmission  and methods as start, and accelerate: