Object-Oriented Programming
OOP organizes code around objects — instances of classes that bundle data and behavior. C# is built on four pillars of OOP.
The Four Pillars
- Encapsulation — hide internal details, expose a public interface
- Inheritance — create new classes based on existing ones
- Polymorphism — treat different types through a common interface
- Abstraction — model real-world concepts, hide complexity
Class Hierarchy Example
public class Animal
{
public string Name { get; protected set; }
public int Age { get; set; }
public Animal(string name, int age)
{
Name = name;
Age = age;
}
public virtual string Speak()
{
return "...";
}
public override string ToString()
{
return $"{Name} (age {Age})";
}
}
public class Dog : Animal
{
public string Breed { get; set; }
public Dog(string name, int age, string breed)
: base(name, age)
{
Breed = breed;
}
public override string Speak()
{
return "Woof!";
}
}
public class Cat : Animal
{
public Cat(string name, int age) : base(name, age) { }
public override string Speak()
{
return "Meow!";
}
}
Polymorphism in Action
List<Animal> animals = new()
{
new Dog("Rex", 5, "Labrador"),
new Cat("Whiskers", 3),
new Dog("Buddy", 2, "Poodle")
};
foreach (Animal animal in animals)
{
// Each calls its own Speak() implementation
Console.WriteLine($"{animal.Name} says {animal.Speak()}");
}
// Rex says Woof!
// Whiskers says Meow!
// Buddy says Woof!
Access Modifiers
| Modifier | Access |
|---|---|
public |
Anywhere |
private |
Same class only |
protected |
Same class + derived |
internal |
Same assembly |
protected internal |
Same assembly or derived |