Skip to main content

Command Palette

Search for a command to run...

OOP — Deconstructing OOP.

Published
•6 min read•View as Markdown

OOP stands for Object Oriented Programming and is a type of programming that is based on objects and classes, which can store data and code and have multiple use cases. OOP is by far the most popular programming paradigm and has become very important for every aspiring software engineer to learn as it is the standard way to code.

By creating a broad design that facilitates the construction of numerous instances that can function on their own, object-oriented programming attempts to break down a program into a set of reusable code pieces.

This enables comparable instances with distinct purposes, analogous to how there are different sorts of a particular thing, such as a car, which comes in several models but is still a car and can do a set of similar activities. In this situation, the essential qualities of the automobile can be compared to a ‘class,’ which is similar to blueprints in that it defines how a car will work and behave. An object in this case would be any sort of car that is produced from that class. If we were to design an electric car, we could duplicate some of this blueprint and change it somewhat; this copying process is known as an inheritance in OOP.It is used to duplicate the blueprint of another class, after which you can change the properties of the parent class.

Object-oriented programming allows us to create reusable objects that can be used across our program, allowing us to compartmentalize several features and create some state around it and each instance of it. Debugging OOP code is also easier because we can trace the fault within our programs more quickly.

KEY CONCEPTS IN OOP

  1. Encapsulation: refers to the ability to conceal information, or, in the case of OOP, how to conceal specific information and control access to it. It is vital to have some access control when defining a blueprint for an object to retain some core state requirements.

  2. Inheritance is concerned with when one class imitates another. Similar to a parent-child relationship in which the child possesses the features of the parent. This is beneficial when building a new object that wants some extra features in addition to the previous object’s features. You can inherit the old class when defining the new class with the extra features and then add some more characteristics to it.

  3. Polymorphism refers to an object’s ability to take on numerous forms or behaviors. This means that things can have multiple capabilities depending on their context. Polymorphism is performed by overriding (rewriting existing data) and overloading (updating existing data), where methods with the same name but different parameters or implementations can be used in different scenarios to get different effects.

  4. Abstraction: the practice of decreasing complexity by concealing unneeded elements while emphasizing vital features. This means that while designing an object, you only show the user the information that is necessary while hiding the implementation details that aren’t. This contributes to the program’s simplification, making it easier to comprehend, develop, and maintain.

  5. A class is a blueprint or template that specifies an object’s attributes and operations. It offers a fundamental framework for producing objects of a particular type.

  6. An object is a specific instance of a class that includes data and data manipulation methods. Each object has its own set of properties and methods that can be used to manipulate its data after being formed from the blueprint provided by the class.

  7. Constructor: When an object is generated from a class, a unique method is called. The object’s properties are initialized and made ready for use with the help of this.

  8. A method is a function connected to an object that is used to alter the data of the object. The data of the object can be retrieved, updated, or deleted using several methods.

  9. Data for an object is stored in an instance variable, which is a variable connected to the object. Instance variables are available for each object and can be used to store and change data.

IMPLEMENTATION

( Getting our hands dirty) : Building an accounts system using OOP and C#

using System;

// Defining an Account class
class RegularAccount
{
    // instance variables
    private int accountNumber;
    private string accountName;
    protected double balance;

    // Constructor to initialize instance variables
    public RegularAccount(int accNum, string accName, double initBalance)
    {
        accountNumber = accNum;
        accountName = accName;
        balance = initBalance;
    }

    // Method to deposit money into the account
    public void deposit(double amount)
    {
        balance += amount;
        Console.WriteLine("Deposited: ${0}", amount);
    }

    // Method to withdraw money from the account
    public virtual void withdraw(double amount)
    {
        if (balance >= amount)
        {
            balance -= amount;
            Console.WriteLine("Withdrawn: ${0}", amount);
        }
        else
        {
            Console.WriteLine("Insufficient balance.");
        }
    }

    // Method to display account details
    public void displayAccountDetails()
    {
        Console.WriteLine("Account Number: {0}", accountNumber);
        Console.WriteLine("Account Name: {0}", accountName);
        Console.WriteLine("Balance: ${0}", balance);
    }
}

// Defining a SavingsAccount class that inherits from the account
class SavingsAccount : RegularAccount
{
    // instance variables
    private double interestRate;

    // Constructor to initialize instance variables
    public SavingsAccount(int accNum, string accName, double initBalance, double intRate) : base(accNum, accName, initBalance)
    {
        interestRate = intRate;
    }

    // Method to calculate and add interest to the account balance
    public void addInterest()
    {
        double interest = balance * interestRate / 100;
        Deposit(interest);
        Console.WriteLine("Added interest: ${0}", interest);
    }

    // Method to withdraw money from the account (overrides the account Withdraw method)
    public override void withdraw(double amount)
    {
        if (balance - amount >= 100)
        {
            balance -= amount;
            Console.WriteLine("Withdrawn: ${0}", amount);
        }
        else
        {
            Console.WriteLine("Insufficient balance.");
        }
    }
}

// Main program
class Program
{
    static void Main(string[] args)
    {
        // Creating a RegularAccount object
        BankAccount acc1 = new RegularAccount(1001, "John Doe", 5000);
        acc1.displayAccountDetails();

        // Depositing and withdrawing from the RegularAccount object
        acc1.deposit(1000);
        acc1.withdraw(2000);
        acc1.displayAccountDetails();

        // Creating a SavingsAccount object
        SavingsAccount acc2 = new SavingsAccount(2001, "Jane Doe", 10000, 2.5);
        acc2.displayAccountDetails();

        // Depositing and withdrawing from the SavingsAccount object
        acc2.deposit(2000);
        acc2.withdraw(5000);
        acc2.displayAccountDetails();

        // Adding interest to the SavingsAccount object
        acc2.addInterest();
        acc2.displayAccountDetails();
    }
}

This code defines two classes, RegularAccount and SavingsAccount, and demonstrates how to create objects from them.

The RegularAccount class has instance variables for account number, account name, and balance, it also has methods for depositing and withdrawing money as well as displaying account details. The class constructor initializes these variables when a new object is created.

The SavingsAccount class inherits from RegularAccount and tweaks it by adding an instance variable for interest rate, it also adds a method for adding interest to the accounts balance. The class constructor calls the base constructor to initialize the RegularAccount variables since it is inherited from the RegularAccount.

The Main method creates objects from both classes and calls various methods on them to deposit and withdraw money, add interest, and display account details. The main method acts as a way to demonstrate how the objects can be used within a program. Using a functional-based approach to this can be quite limiting as that would involve having a specific program for each instance of the object, this is solved wholly with Object Oriented Programming.

In addition, the SavingsAccount class overrides the withdraw method of the RegularAccount class specifies that a withdrawal is only possible if the account balance is greater than or equal to 100 after the withdrawal is made.

In conclusion, this code demonstrates the use of inheritance and polymorphism in object-oriented programming, as well as basic concepts of encapsulation and class constructors in C#. It uses a real-life concept to properly explain OOP.