Class in Object-Oriented Programming
A class is a blueprint for creating objects in Object-Oriented Programming (OOP). It defines the structure and behavior that the objects will have. A class consists of attributes (fields) and methods (functions) that define what an object can do.
Why Are Classes Important?
- Encapsulation of Data: A class groups related data and behavior together.
- Reusability: Once a class is defined, multiple objects can be created from it.
- Modularity: Classes promote clean, organized, and maintainable code.
How Classes Work
In C#, a class is defined using the class
keyword and can contain fields, properties, constructors, and methods.
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 from the Class
var account1 = new BankAccount("Alice", 500);
var account2 = new BankAccount("Bob", 1000);
// Using Methods
account1.Deposit(200);
Console.WriteLine($"Balance for Alice: {account1.GetBalance()}");
account2.Deposit(300);
Console.WriteLine($"Balance for Bob: {account2.GetBalance()}");
Key Takeaways:
- A class (
BankAccount
) defines the structure of objects.
- Objects (
account1
, account2
) are created based on the class blueprint.
- The class includes methods (
Deposit
, GetBalance
) that operate on its attributes.
Conclusion
Classes are the foundation of OOP, providing a structured way to define objects and their behaviors. Understanding classes is essential for writing reusable and scalable code.
In the next articles, we will explore more Object-Oriented Programming principles such as Inheritance and Polymorphism, continuing with our structured examples.