DEV Community

Cover image for Mastering OOPS: Encapsulation and Abstraction Explained Simply
Jai Desai
Jai Desai

Posted on

Mastering OOPS: Encapsulation and Abstraction Explained Simply

Lets Recall Previous Articles

OOP Basics
Classes and Objects:
1. Class: A blueprint for creating objects.
2. Object: An instance of a class.
3. Attributes: Data stored in objects (e.g., make, model).
4. Methods: Functions that operate on objects (e.g., drive)

Inheritance
1.Definition: A mechanism where one class inherits attributes
and methods from another class.
2.Example: A 'Dog' class inherits from an 'Animal' class,
gaining it's properties and behaviors.

Polymorphism
1.Definition: The ability of different objects to respond in
unique ways to the same method call.
2.Example: Both 'Dog' and 'Cat' classes inherit from 'Animal',
but each implements the makeSound method differently ('Dog'
barks, 'Cat' meows).

Encapsulation
Encapsulation is like putting your data in a box and only
allowing access through controlled methods. It protects the data
inside from unauthorized access and modifications.

Example Explanation
Imagine a class 'Person' that has private attributes 'name' and 'age'. You can't access these directly from outside the class. Instead,you use public methods to get and set these values.

code

Image description

// Continue the example

Image description

Image description

Image description

Abstraction
Abstraction is like using a remote control to operate your TV.
You don't need to know how the TV works internally; you just
need to know which buttons to press.

Example Explanation
Imagine an abstract class 'Animal' that has an abstract method 'makeSound()'. Different animals will have their own implementation of 'makeSound()', but you don't need to know the details when you call this method.

Image description

// continue the example

Image description

Summary

  • Encapsulation: Protects data by keeping it private and providing public methods to access and update it.

1.Example: The 'Person' class with private attributes and
public getter and setter methods.

  • Abstraction: Hides complex details and shows only the essential features of an object.

2.Example: The 'Animal' abstract class with an abstract
method 'makeSound()' that is implemented differently in 'Dog'
and 'Cat' subclasses.

We dive into more in next article

Top comments (0)