Four Principles of Object-Oriented Programming with Examples in C#

I enjoy object-oriented programming. I understand the concepts, but I’ve found that when asked to define or show an example of the basic principles my brain blanks. This especially happens in pressure situations like interviews. So this post gets to act as my memory until the four principles of object-oriented programming (encapsulation, inheritance, polymorphism and abstraction).

Encapsulation

Encapsulation is the idea that the attributes of an entity are enclosed in that entity. This gives context to attributes. This also allows the programmer to restrict access to those attributes so that those attributes are modified and/or used only in ways that the programmer intends to use them.

Inheritance

Inheritance is the idea that an entity can inherit attributes from another entity. It allows the programmer to create similar entities without needing to redefine similar attributes over and over.

This means every Dog, Cat and Bird (derived classes) will have a name and age variable as well as a Identify method because they are Animals (base class).

Polymorphism

Polymorphism means “having many forms” which honestly doesn’t really help too much as a definition.  I like to call it a way to have the same method, only different. There are two ways to do this:

  • Overloading: The method name stays the same, but the parameters, the return type and the number of parameters can all change.
  • Overriding: This is when a derived class method has the same name, parameters and return type as a method in a base class but has a different implementation.

    Overriding can get a bit wonky depending on how you instantiate a object of a derived class. I suggest reading Knowing When to Use Override and New Keywords slowly.

Abstraction

Abstraction is the process of hiding all but the relevant information about a thing to make things less complex and more efficient for the user. For example, we don’t need to know how a clock works in order to use it to tell time. Abstraction lets you focus on what the thing does instead of how it does it.

As much as I tried to keep thins post brief, I failed. If I got something wrong, or if something doesn’t make sense please reach out and let me know.

Here are a few of the resources I used:

Leave a Reply