DEV Community

Cover image for A Journey into Object Oriented Programming
Justine Kimeli
Justine Kimeli

Posted on

A Journey into Object Oriented Programming

Introduction

Learning programming has introduced me how to write variables, conditions, loops, and functions. These are the concepts that helped me create simple programs, but as programs became larger, I realized that organizing the code could become difficult.
This is where OOP comes in. OOP is simply a way of organizing a program so that it is easier to understand and manage.
This article will entail what OOP is, class and objects and its four main pillars.

What is OOP?

Object-Oriented Programming(OOP) is a programming approach that organizes software around objects and classes rather than only functions and procedures.

Classes and Objects

A class is a blueprint or plan for creating objects. For example, a Student is a class that decribe what information and actions a should have.

An object is an actual thing created from class. Basically, it is an instance of a class. For example, a student called James from Student class.
An example:

class Student:
    def __init__(self, name,age):
        self.name = name
        self.age = age

    def display_info(self):
        print(f"My name is {self.name} and I am {self.age} years old")

s1 = Student("James", 28)
s1.display_info()
Enter fullscreen mode Exit fullscreen mode

In the above program Student is the class, while s1 is an object. The display_info() function is a method that describes information about the student

Four Pillars of OOP

Object Oriented Programming has four main pillars: encapsulation,inheritance, ** polymorphism** and abstraction.

1.Encapsulation

Encapsulation means keeping related data and methods together inside a class. It protects data from direct access.
An example is a class bank account, it contains account balance and methods of depositing or withdrawing money. Instead of changing tha balance directly, it can be accessed through the methods provided by the class.
__Example

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance


account = BankAccount(1000)

account.deposit(500)

print(account.get_balance())
Enter fullscreen mode Exit fullscreen mode

The balance is kept inside the BankAccount class. The __balance is not meant to be accessed directly. We use methods such as deposit() and get_balance() to work with it.

2. Inheritance

In basic terms, inheritance allows a new class to (child/ sub/ derived class) re-use the attributes and methods of an existing class(parent/ super/base class).
Example:

# Parent CLass
class FarmAnimal:
    def __init__(self, name, age, weight):
        self.name = name
        self.age = age
        self.weight = weight

    def eat(self):
        print(f"{self.name} is eating")

    def display_detail(self):
        print(f"Name: {self.name} \nAge: {self.age} \nWeight: {self.weight}")

class Cow(FarmAnimal):
    def __init__(self, name, age, weight, milk_per_day):
        super().__init__(name,age, weight)

    def produce_milk(self):
        print(f"{self.name} produces {self.milk_per_day} litres per day")

    def milk_monthly(self):
        return self.milk_per_day * 30



# Child class 2 
class Chicken(FarmAnimal):
    def __init__(self, name, age, weight, eggs_per_week):
        super().__init__(name, age, weight)
        self.eggs_per_week = eggs_per_week


    def produce_eggs(self):
        print(f"{self.name} produces {self.eggs_per_week} per week.")

    def monthly_eggs(self):
        return self.eggs_per_week * 4

ingokho = Chicken("Ingokho", 2, 2 , 10)
ingokho.monthly_eggs()
ingokho.display_detail()
Enter fullscreen mode Exit fullscreen mode

Both class Cow and Chicken inherit attributes from class FarmAnimal

3. Polymorphism

It allows same method to behave differently. For example Cow and Chicken demonstrate polymorphism by using same method name but diffrent behavior.

class Cow(FarmAnimal):
    def make_sound(self):
        print("The cow says Moo!")


class Chicken(FarmAnimal):
    def make_sound(self):
        print("The chicken says Cluck!")
cow = Cow("Bessie", 4, 400, 15)
chicken = Chicken("Ingokho", 2, 2, 10)

cow.make_sound()
chicken.make_sound()
Enter fullscreen mode Exit fullscreen mode

The method has same name, make_sound(), but behaves differently depending on the object is what we call polymorphism.

4. Abstraction

This is hiding complicated details and showing only what is necessary to the user.
An example is here:


class Car:
    def start(self):
        self.__start_engine()
        print("Car is ready to move")

    def __start_engine(self):
        print("Engine started")


car = Car()

car.start()
Enter fullscreen mode Exit fullscreen mode

We call car.start(), we do not need to know how the engine starts internally. The complicated process is hidden inside __start_engine() and we only use the simple start() method.

Conclusion

Learning OOP has helped me understand that programming is not only about writing lines of code but also about organizing those lines of code in a way that makes sense.
Discovering how all the concepts work together yields a better understanding that classes, objects, methods, inheritance, encapsulation, polymorphism, and abstraction are important tools for creating organized and reusable programs.

Top comments (0)