Skip to main content
Practice

Encapsulation and Polymorphism, Core Concepts of Object-Oriented Programming

Encapsulation and Polymorphism are also key concepts in object-oriented programming.

In this lesson, we will introduce the concepts of encapsulation and polymorphism, and see how to use them in Python.


What is Encapsulation?

Encapsulation refers to the practice of protecting an object's state by restricting direct access to its internal data.

The internal data of an object cannot be accessed directly from outside; it can only be manipulated through public methods.

This ensures data integrity (accuracy and consistency of data) and keeps the object's state safe.

Encapsulation Example
class Car:
def __init__(self, speed):
self.__speed = speed # Setting the speed attribute as private, __ denotes a private attribute

def get_speed(self):
return self.__speed # Returning the encapsulated attribute

def set_speed(self, speed):
if speed > 0:
self.__speed = speed # Modifying the encapsulated attribute

my_car = Car(50)

# Output: 50
print(my_car.get_speed())

In the example above, the __speed attribute is encapsulated and is in a private state, so it cannot be accessed directly from outside.

The __speed attribute can only be manipulated through the get_speed and set_speed methods.

Attempting to access the attribute directly with my_car.__speed would result in an error, thereby ensuring data integrity.


What is Polymorphism?

Polymorphism refers to the ability of different objects to respond, each in its own way, to identical messages (or method calls).

This greatly enhances the flexibility and extensibility of code.

Method overriding, where a method defined in a parent class is redefined in a child class, is a representative example of polymorphism.

Polymorphism Example
class Animal:
def speak(self):
return "Makes a sound"

class Dog(Animal):
def speak(self):
return "Bark"

class Cat(Animal):
def speak(self):
return "Meow"

animals = [Dog(), Cat()]

for animal in animals:
# Calls the overridden speak method in Dog and Cat classes
print(animal.speak())
# Output: "Bark" and "Meow" on different lines

In the example above, the speak method defined in the Animal class behaves differently in the Dog and Cat classes.

This demonstrates polymorphism, as the same method call can result in different outcomes depending on the object.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.