Encapsulation

788 views

I’ve been learning C# over the past while, and as a result, I’ve been learning a lot about Object Oriented Programming concepts. I have a rather good understanding of classes and inheritance and am about to learn about polymorphism, but one concept I currently can’t wrap my head around is encapsulation. I just can’t understand what it does or why it’s even used in any sense. Any help would be appreciated, because I’d rather move forward having a good understanding of every c# concept I’ve touched on so far before moving on to new things.

In: Other

4 Answers

Anonymous 0 Comments

Wow I really learned encapsulation differently. Encapsulation is actually a very simple principle: limit access to data from the outside world and gather together related parts of a program together in one place, a class.

The first principle makes you think about the data a class will need to operate. The immediate data you need should be closed off from the outside world modifying it at will but allow access to it through the proper use of things like constructors, getters, and setters. Data fields in a class should generally be private as well and access to them are through the 3 methods mentioned above. You really don’t have many global variables in a in an OOP program. If you find the need for globals, they get encapsulated in a class instead of floating around the entire program.

The second principle speaks to the methods a class implements. A User class might implement methods to log a user in, fetch the parts of a system they can interact with, log a user out and so on. These methods are gathered together in one place because they will operate on the same data and placing them in the same class is a logical solution to organize your code.

To me, encapsulation doesn’t necessarily state that methods are there to abstract away implementation details of complex systems. You could write a .cpp with a myriad of complex functions and claim encapsulation because the user just has to call a function to perform a complex operation. There are patterns you can follow that help to abstract away complexity if that’s your aim.

You are viewing 1 out of 4 answers, click here to view all answers.