Constructors in Object-Oriented Programming

A constructor is a special method in Object-Oriented Programming (OOP) that is automatically called when an object is created. It is used to initialize the object's properties and ensure the object starts in a valid state.

Why Use Constructors?

  • Automatic Initialization: Ensures that objects are initialized with the required values.
  • Improves Code Readability: Makes object creation more structured and meaningful.
  • Encapsulation Support: Helps maintain control over object creation and prevents invalid states.

How Constructors Work

In C#, a constructor has the same name as the class and does not return any value.

Example:

class BankAccount
{
    private double balance;
    private string owner;

    // Constructor
    public BankAccount(string owner, double initialBalance)
    {
        this.owner = owner;
        balance = initialBalance > 0 ? initialBalance : 0;
        Console.WriteLine($"Account created for {owner} with balance {balance}");
    }

    public void Deposit(double amount)
    {
        if (amount > 0)
        {
            balance += amount;
            Console.WriteLine($"Deposited: {amount}");
        }
    }

    public double GetBalance()
    {
        return balance;
    }
}

var account = new BankAccount("John Doe", 1000);
account.Deposit(500);
Console.WriteLine($"Current Balance: {account.GetBalance()}");

Key Takeaways:

  • The constructor is named BankAccount and is automatically called when an object is created.
  • It ensures that every BankAccount object starts with a valid owner and balance.
  • The constructor prevents negative initial balances by setting them to 0 if necessary.

Conclusion

Constructors help ensure that objects are always in a valid state when they are created. They improve code structure, prevent errors, and enhance maintainability.

In the next articles, we will explore other Object-Oriented Programming principles such as Inheritance and Abstraction using a consistent example structure.