Object-Oriented Programing: Overview


Object-Oriented Programming is a programming paradigm that aims to help software developers and engineers create elegant software. This in turn helps to create a simple approach that’s universal to developers. It is highly recommended to have a solid understanding of Classes and Objects as they are fundamental tools used in OOP.

The four main pillars of Object-Oriented Programming are listed below:

  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritance

Throughout this article, we’ll discuss the pillars and how they play a role in the paradigm of object-oriented programming.

Inheritance

Inheritance is a practice of “inheriting” traits from a parent class. The parent class is referred to as a superclass or base class, and the class inheriting properties from the superclass is formerly known as the subclass or child class. For example, let’s say we define a base class with the name Dog:

class Dog // base class (parent) 
{

  public void bark()// Dog bark method 
  {                    
    Console.WriteLine("Dog is barking");
  }

  public void sit()// Dog sit method 
  {                    
    Console.WriteLine("Dog is sitting");
  }

  public void eat()// Dog eat method 
  {                    
    Console.WriteLine("Dog is eating");
  }

}

Within this class we’ve defined 3 methods:

  • bark()
  • sit()
  • eat()

When these methods are invoked, they perform operations based on what they are instructed to do inside the methods. Which defines default methods for all subclasses that inherit traits from the Dog class.

To show that this works, let’s create a subclass called MyDog which will ideally be the name of the dog and inherit properties from the Dog class:

class MyDog : Dog  // derived class (child)
{
  public string breedName = "German Shepherd";  // MyDog field
}

I can then create an Object called MyDog and utilize the Dog methods that the class inherits from:

class Program
{
  static void Main(string[] args)
  {
    // Create a MyDog object
     MyDog gatsby = new MyDog();

    // Call the bark() method (From the Dog class) on the gatsby object
    gatsby.bark();

    // Display the value of the MyDog field (from the MyDog class) 
    Console.WriteLine(gatsby.breedName);
  }
}