DEV Community

Jai Desai
Jai Desai

Posted on

Object Oriented Programming (OOP) Made Simple!

Object-Oriented Programming (OOP) is a way of writing computer programs that focuses on creating objects that contain both data (attributes) and functionality (methods).

Example: Car Object

Imagine we want to model a car in a computer program using OOP principles.

  1. Class Definition:
  • A class is like a blueprint or template for creating objects. For our car example, the class defines what a car is and what it can do.

class Car:
def init(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer = 0 # Initial odometer reading

def drive(self, distance):
    self.odometer += distance
    print(f"The {self.year} {self.make} {self.model} has 
    driven {distance} miles.")
Enter fullscreen mode Exit fullscreen mode
  • In this example:
    Car is the class that represents a car.

  • init method (constructor) initializes a new car object with attributes like make, model, year, and odometer.

  • drive method simulates driving the car and updates the odometer.

  1. Creating Objects (Instances):
  • An object is an instance of a class. We can create multiple cars (objects) based on our Car class.

code-
# Create instances (objects) of the car class
my_car = Car("Toyota", "Camry", 2022)
your_car = Car("Honda", "Accord", 2020)

#use the objects (instances)
my_car.drive(100)
your_car.drive(50)

  • my_car and your_car are objects (instances) of the Car class.

  • We can use the drive method on each car object to simulate driving and update their odometers.

  1. Encapsulation:
  • It means mechanism of wrapping the data and hiding the implementation details
  1. Inheritance and Polymorphism:
  • Inheritance allows us to create a new class based on an existing class, inheriting its attributes and methods. For example, we could create a ElectricCar class that inherits from Car and adds additional features like charge_battery'.

  • Polymorphism allows objects to be treated as instances of their parent class. For example, both Car and ElectricCar objects can be treated as Car objects when methods like drive are called.

Summary:

  • Class is a blueprint for creating objects.

  • Object is an instance of a class.

  • Attributes are data stored in objects (e.g., make, model).

  • Methods are functions that operate on objects (e.g., drive).

Explaining more Details about Inheritance and Polymorphism in next article. And if you have any doubt so please write on comments and please give me feedback!!
Thanks!

Top comments (1)

Collapse
 
jaid28 profile image
Jai Desai

Thanks to everyone who just like my article and if you have any doubt or if you want to give me feedback so please ask me freely