- Encapsulation: Bundling data and methods that operate on the data within a single unit (class).
- Inheritance: Deriving new classes from existing ones, enabling code reuse.
- Polymorphism: Allowing methods to do different things based on the object it is acting upon.
- Abstraction: Hiding complex implementation details and exposing only the necessary parts.
Example in C#
Here's a simple example illustrating these concepts:
csharp// Encapsulation and Abstraction
public class Animal
{
// Property
public string Name { get; set; }
// Method
public virtual void Speak()
{
Console.WriteLine("Animal speaks");
}
}
// Inheritance
public class Dog : Animal
{
// Overriding the Speak method for Dog
public override void Speak()
{
Console.WriteLine("Woof! Woof!");
}
}
// Inheritance
public class Cat : Animal
{
// Overriding the Speak method for Cat
public override void Speak()
{
Console.WriteLine("Meow!");
}
}
// Polymorphism
class Program
{
static void Main(string[] args)
{
// Creating objects of Dog and Cat
Animal myDog = new Dog();
Animal myCat = new Cat();
// Polymorphic behavior
myDog.Speak(); // Outputs: Woof! Woof!
myCat.Speak(); // Outputs: Meow!
}
}
Explanation:
- Encapsulation: The
Animalclass encapsulates theNameproperty and theSpeakmethod. - Inheritance:
DogandCatclasses inherit from theAnimalclass, allowing them to use its properties and methods. - Polymorphism: The
Speakmethod is overridden in bothDogandCat, enabling each to provide its own implementation while being referenced asAnimal. - Abstraction: The user interacts with the
Speakmethod without needing to understand the underlying details of how each animal speaks.
This example showcases how OOP principles can be effectively used in .NET.






