Object in Object-Oriented Programming
An object is a fundamental unit in Object-Oriented Programming (OOP). It is an instance of a class that encapsulates data (attributes) and behavior (methods). Objects are created based on class blueprints and allow interaction with data in a structured way.
Why Are Objects Important?
- Encapsulation of Data: Objects store and manage data securely.
- Reusability: Objects can be reused across different parts of a program.
- Interaction with Other Objects: Objects work together to form complex systems.
How Objects Work
In C#, objects are created using the new
keyword to instantiate a class.
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 Objects
var account1 = new BankAccount("Alice", 500);
var account2 = new BankAccount("Bob", 1000);
// Using Object Methods
account1.Deposit(200);
Console.WriteLine($"Balance for Alice: {account1.GetBalance()}");
account2.Deposit(300);
Console.WriteLine($"Balance for Bob: {account2.GetBalance()}");
Key Takeaways:
- Objects (
account1
, account2
) are instances of the BankAccount
class.
- Each object has its own unique state (
owner
, balance
).
- Methods interact with the object's data and modify its state.
Conclusion
Objects are the core building blocks of OOP. They allow structuring code in a modular and reusable way. Understanding how to create and use objects effectively is crucial for mastering OOP.
In the next articles, we will explore more Object-Oriented Programming principles such as Interfaces and Polymorphism, continuing with our structured examples.