I will be discussing Encapsulation for the finale, or part four, of my Object Oriented Programming series:

  1. Abstraction
  2. Inheritance
  3. Polymorphism
  4. Encapsulation – Current Post


John Mitchell has an excellent definition of encapsulation: “A language mechanism for restricting direct access to some of the object’s components.” 

If you work with programming languages such as C#, you will notice that you can make variables, functions, and even classes private. When you make one of these private, you’re restricting access to it. For example, when you make a class field private, only the class it’s inside of can access the variable. If you want to read the value of the field from another class, you would have to create a public method that returns the value.

Let’s say that I have a Yorkshire Terrier class with a private ‘Breed’ field and a corresponding public method that returns the value of that field.

Class Yorkshire Terrier
  private Breed = “Yorkshire Terrier”;

  public GetBreed()
    return Breed;

When I call the function GetBreed(), I get “Yorkshire Terrier”. Now, why wouldn’t I just make the field public instead of private? This is because we’re writing code for our present and future self. Also, generally you’re not the only person working on the code. There’re other programmers who need to be able to read and modify your code. Thus, when you make a class field private, you’re preventing your future self or other programmers from accidentally modifying its value. Imagine setting the Breed field of the Yorkshire Terrier class as a Golden Retriever. If you don’t realize this mistake right away, then it might take some time to figure out where you set the field. Encapsulation helps minimize complexity. By keeping certain components private, we protect the code from ourselves.


This is the end of my OOP series. These principles helped me make the mental shift from functional programming to Object Oriented Programming. I continue to refer to them as I build software. I encourage you to find ways to implement these principles into your code.

Share This