In our previous lesson on Abstraction, we abstracted a few lines into a new method on the same class. Now using the idea of Encapsulation we take this one step further. Instead of a method, we can create a new class and add the method there. That class would then be the place we’d put similar methods in the future.
Another way to think about Encapsulation is when you spot you have many similar methods, perhaps spread across many classes. To make the code more manageable we could use Encapsulation to create a single class and refactor all those methods on to that class. This would then group those similar methods into once place, into one well-named class.
In the programming basics course, we have Public, Private, Protected and Internal.
As mentioned they control access, which is something really important to consider when thinking about Encapsulation. As mentioned in the basics course, a part of encapsulation is data hiding. Something we achieve using Access Modifiers. Here are the basic rules in C#.
|Containing Class||Extended Class / Same Package||Any Class||Other Project|
Please look at the links above for full code examples which are heavily documented. Too many classes and a lot of code to paste into the post.
You can see some of the errors presented by VS here due to the incorrect access levels