DEV Community

Cover image for Classes in Object-Oriented Programming (OOP)
Wangare
Wangare

Posted on • Edited on

Classes in Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a powerful paradigm that helps us structure code to model real-world concepts and relationships. At the heart of OOP lies the concept of a Class.

What is a Class?

In simple terms, a class is a blueprint, a template, or a prototype from which objects are created.

It's a logical entity that defines the data (attributes) and the behavior (methods) that all objects created from it will possess.

Classes don't consume memory until an object (an instance of the class) is created.

Think of a class like the blueprint for a house:

  • The blueprint specifies the number of rooms, the materials, and the layout (this is the class).
  • The actual houses built from that blueprint are the objects (or instances).

Why Are Classes Useful? (The Power of Abstraction and Encapsulation)

Classes bring structure and organization to your code, offering several key benefits:

  • Abstraction: Classes allow you to define a complex entity (like a BankAccount or a Car) in a simple, understandable way, hiding the complex internal workings. The user only needs to know what the object can do, not how it does it.

  • Encapsulation: This is the practice of bundling data (attributes) and the methods that operate on that data into a single unit (the class). It protects the data from accidental modification by restricting direct access.

  • Code Reusability: Once a class is defined, you can create many different objects (instances) from it, each with its own state, without having to rewrite the foundational logic.

Anatomy of a Class: Attributes and Methods

A class is composed of two primary components:

1. Attributes (Data/State)

Attributes are variables defined within the class that hold the state or data of an object. For a Dog class, attributes might include breed, color, and age.

2. Methods (Behavior/Functions)

Methods are functions defined within the class that represent the actions or behavior an object can perform. They can also manipulate the object's attributes. For a Dog class, methods might include bark(), fetch(), and sleep().

🏦 Example: The BankAccount Class

Let's demonstrate these concepts by creating a simple BankAccount class. For this example, we'll use Python syntax, which is widely used for illustrating OOP concepts.

1. Defining the Class

class BankAccount:
    # 1. The Constructor Method (__init__)
    # This method is automatically called when a new object is created.
    # It sets the initial state (attributes) of the object.
    def __init__(self, account_number, owner, initial_balance=0):
        # Attributes
        self.account_number = account_number
        self.owner = owner
        self.balance = initial_balance

    # 2. Methods (Behaviors)
    def deposit(self, amount):
        if amount > 0:
            self.balance += amount
            print(f"Deposit of ${amount:.2f} successful.")
        else:
            print("Deposit amount must be positive.")

    def withdraw(self, amount):
        if amount > 0 and self.balance >= amount:
            self.balance -= amount
            print(f"Withdrawal of ${amount:.2f} successful.")
            return True
        elif amount <= 0:
            print("Withdrawal amount must be positive.")
            return False
        else:
            print("Error: Insufficient funds.")
            return False

    def check_balance(self):
        print(f"Account Balance for {self.owner}: ${self.balance:.2f}")
        # Note: We use 'self' to access the object's own attributes.
Enter fullscreen mode Exit fullscreen mode

2. Creating and Using Objects (Instantiation)

To use the class, you must create an object (or instance) from it. This process is called instantiation.

# Creating the first object: an account for Alice
alice_account = BankAccount(
    account_number="12345", 
    owner="Alice Smith", 
    initial_balance=500.00
)

# Creating the second object: an account for Bob
bob_account = BankAccount(
    account_number="67890", 
    owner="Bob Johnson"
    # initial_balance defaults to 0
)

print("--- Initial State ---")
alice_account.check_balance() 
# Output: Account Balance for Alice Smith: $500.00
bob_account.check_balance()   
# Output: Account Balance for Bob Johnson: $0.00

# Performing Operations (Calling Methods)
print("\n--- Performing Operations ---")
alice_account.deposit(250.75)
alice_account.check_balance()
# Output: Deposit of $250.75 successful.
# Output: Account Balance for Alice Smith: $750.75

bob_account.withdraw(50.00)
# Output: Error: Insufficient funds.

bob_account.deposit(100.00)
bob_account.withdraw(50.00)
bob_account.check_balance()
# Output: Deposit of $100.00 successful.
# Output: Withdrawal of $50.00 successful.
# Output: Account Balance for Bob Johnson: $50.00
Enter fullscreen mode Exit fullscreen mode

Key Takeaway

Notice how the alice_account and bob_account objects are completely separate. They both use the same blueprint (BankAccount), but they hold their own unique values for the attributes (owner, balance, etc.).

This is the essence of OOP: using classes to create organized, modular objects that perfectly model the real-world entities and behaviors in your program. Your code is now structured like a system of interacting components, making it easier to build, maintain, and scale complex applications.

Top comments (0)