Can you explain the four main principles of OOP (Encapsulation, Abstraction, Inheritance, and Polymorphism) and provide a brief example of how you've used one of them in a project, perhaps in C#?

Object-Oriented Programming (OOP) is built on four core principles:

  1. Encapsulation – Restricting access to certain details of an object and exposing only what's necessary. This is achieved using access modifiers (private, public, protected), ensuring that data is only accessed through controlled mechanisms like properties or methods.

  2. Abstraction – Hiding implementation details and exposing only the relevant operations. This helps simplify complex logic, allowing users to interact with an object without needing to understand how it works internally. Abstract classes and interfaces are commonly used for this purpose.

  3. Inheritance – Allowing a class to inherit properties and behavior from another class. This promotes code reuse and creates hierarchical relationships. In C#, the : symbol is used to denote inheritance (class Car : Vehicle means Car inherits from Vehicle).

  4. Polymorphism – Enabling objects to take many forms. This allows methods to be overridden (override keyword) or to behave differently based on the object calling them. It’s useful for achieving flexibility in handling different types of objects through a unified interface.

Example in C#

A practical application of polymorphism would be defining a base class for different types of employees in a system:

class Employee
{
    public virtual void Work() => Console.WriteLine("Employee is working.");
}

class Developer : Employee
{
    public override void Work() => Console.WriteLine("Developer is writing code.");
}

class Designer : Employee
{
    public override void Work() => Console.WriteLine("Designer is creating visuals.");
}

class Program
{
    static void Main()
    {
        Employee emp1 = new Developer();
        Employee emp2 = new Designer();

        emp1.Work(); // Output: Developer is writing code.
        emp2.Work(); // Output: Designer is creating visuals.
    }
}

Here, different employee types override the Work() method, demonstrating polymorphism—one method, multiple behaviors depending on the object type.