Four Pillars Of Object-Oriented Programming


The four pillars of object-oriented programming are:

#1. Abstraction

  • It is a process of listing out relevant information and discarding irrelevant information (for example, if we have a student entity, the relevant information can be Student ID, Name, Address, Grades, and the irrelevant information could be race, nationality, etc.).
  • Abstract classes or interfaces are used for abstraction.

#2. Encapsulation

  • Group of related properties and methods are treated as a single unit.
  • Classes are used for encapsulation.

#3. Inheritance

  • New classes can be created based on existing classes.
  • The class being inherited is called the base class.
  • The new class being created through inheritance is called the derived class.

#4. Polymorphism

  • Derived classes can have a different implementation of the same methods or properties.
  • Objects of derived class can be treated as objects of base class.
  • Base class can define and implement virtual methods.
  • Derived classes can override the virtual methods of base class.
Example - Polymorphism
namespace MyConsoleApp
{
    class Language
    {
        public virtual void Greeting()
        {
            Console.WriteLine("Hello!");
        }
    }

    class Spanish : Language
    {
        public override void Greeting()
        {
            Console.WriteLine("Hola!");
        }
    }

    class French : Language
    {
        public override void Greeting()
        {
            Console.WriteLine("Bonjour!");
        }
    }
}
Example - Polymorphism implementation
namespace MyConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Language language = new Language();
            Language spanish = new Spanish();
            Language french = new French();
            language.Greeting();
            spanish.Greeting();
            french.Greeting();
        }
    }
}
/* OUTPUT:
 * Hello!
 * Hola!
 * Bonjour!
*/