Instance in Object-Oriented Programming

Instance is a fundamental concept in Object-Oriented Programming (OOP). An instance is an actual object created from a class. When a class is defined, it acts as a blueprint, and an instance is a concrete realization of that blueprint with specific values and behaviors.

Why Are Instances Important?

  • Encapsulation of Data: Each instance has its own copy of instance variables.
  • Code Reusability: Multiple instances can be created from a single class.
  • Supports OOP Principles: Objects interact with each other through instances.

How Instances Work

To create an instance of a class in C#, we use the new keyword. Each instance can have unique properties and behaviors.

Example:

// Class definition
class BankAccount
{
    private double balance;
    private string owner;

    public BankAccount(string owner, double initialBalance)
    {
        this.owner = owner;
        balance = initialBalance > 0 ? initialBalance : 0;
    }

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

    public double GetBalance()
    {
        return balance;
    }
}

// Creating instances of the BankAccount class
var account1 = new BankAccount("John Doe", 1000);
var account2 = new BankAccount("Jane Smith", 2000);

account1.Deposit(500);
Console.WriteLine($"{account1.GetBalance()}");

Key Takeaways:

  • The BankAccount class defines the blueprint for creating bank account objects.
  • account1 and account2 are separate instances of the class.
  • Each instance maintains its own state (e.g., balance and owner).

Conclusion

Instances bring classes to life by allowing real-world representations of objects. They enable object interaction, encapsulation, and data management.

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