Encapsulation
If we talk about Encapsulation it means that we usually bind up the data and methods together and it only provides access through a public interface.
For example, In the context of cars, it means that we are bundling related data and functionality together, like putting a protective proper shield around a car.
Implementation of Encapsulation Methods:
In this example, the “Car” class encapsulates the brand, color, and fuel level of the car. The car can be refueled and driven but the fuel level is protected and only covert through defined methods.
class Car:
def __init__(self, brand, color):
# Initialize car with brand, color, and full fuel tank (fuel_level = 100)
self.brand = brand
self.color = color
self.fuel_level = 100
def refuel(self):
# Refuel the car, setting the fuel level back to 100
self.fuel_level = 100
print("The " + self.color + " " + self.brand + " car has been refueled.")
def drive(self):
# Check if the car has fuel
if self.fuel_level > 0:
# If fuel level is greater than 0, drive the car and reduce fuel level by 10
self.fuel_level -= 10
print("The " + self.color + " " + self.brand + " car is driving.")
else:
# If out of fuel, print a message indicating so
print("The car is out of fuel!")
# Create a Car object
my_car = Car("Toyota", "blue")
# Refuel the car and drive it
my_car.refuel()
my_car.drive()
Output
The blue Toyota car has been refueled. The blue Toyota car is driving.
In this example, the “Car” class encapsulates the brand, color, and fuel level of the car. The car can be refueled and driven but the fuel level is protected and only covert through defined methods.
Object Oriented Programming System (OOPs) For Kids
Object-Oriented Programming System (OOPs) is a way of writing computer programs where we organize code into small, reusable pieces called objects. These objects represent things or concepts in the real world, like cars, animals, or people. Each object has its data and behaviors, and we can use them to build complex programs by connecting them. It’s like building with LEGO bricks, where each brick is a piece of code that we can snap together to create something bigger and more interesting.
Table of Content
- What is Object-Oriented Programming (OOPs)?
- How do OOPs work?
- Why use OOPs?
- Basic Concepts of OOPs
- What is Object in OOPs?
- What is Class in OOPS?
- Example for Class and Object in OOPS
- Abstraction
- Encapsulation
- Inheritance
- Polymorphism
- Benefits of OOPS
- Applications of OOPS
- Conclusion
- OOPs(Object Oriented Programming) – FAQs