OOPs Concepts in C#
OOPs Concepts in C#
Object-Oriented Programming (OOP) is a programming paradigm that revolves around the concept of "objects." These objects have properties (data) and behaviors (methods). C# is a powerful language that fully supports OOP principles. Let's delve into the core concepts:
1. Encapsulation
* Hiding Implementation Details: Encapsulation involves bundling data (attributes) and methods (functions) that operate on that data within a single unit called a class.
* Access Modifiers: C# provides access modifiers like public, private, protected, and internal to control the visibility of class members.
* Example:
public class Person
{
private string name;
private int age;
public void SetName(string name)
{
this.name = name;
}
public string GetName()
{
return name;
}
// ... other methods
}
2. Inheritance
* Creating Hierarchies: Inheritance allows you to create new classes (derived classes) based on existing ones (base classes).
* Code Reusability: Derived classes inherit the properties and methods of their base class, promoting code reuse.
* Example:
public class Animal
{
public void Eat()
{
Console.WriteLine("Eating...");
}
}
public class Dog : Animal
{
public void Bark()
{
Console.WriteLine("Woof!");
}
}
3. Polymorphism
* Multiple Forms: Polymorphism enables objects of different types to be treated as if they were of the same type.
* Method Overloading and Overriding:
* Overloading: Defining multiple methods with the same name but different parameters.
* Overriding: Redefining a virtual method in a derived class.
* Example:
public class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape...");
}
}
public class Circle : Shape
{
public override void Draw()
{
Console.WriteLine("Drawing a circle...");
}
}
4. Abstraction
* Focusing on Essentials: Abstraction involves hiding unnecessary implementation details and exposing only the essential features.
* Interfaces and Abstract Classes:
* Interfaces: Define a contract of methods that a class must implement.
* Abstract Classes: Provide a partial implementation and can contain abstract methods that must be implemented by derived classes.
* Example:
public interface IShape
{
void Draw();
}
public abstract class Shape
{
public abstract void Draw();
}
By understanding and effectively applying these OOP concepts, you can create well-structured, maintainable, and reusable C# applications.
Would you like to explore any of these concepts further or have a specific question about OOP in C#?
Comments
Post a Comment