‘Stupid’ Question 24: Can you give me an easy to remember example of what the different access modifiers do?
Access modifiers - it is easy to mix them up now and then. And if you havent been using them, then you should really consider to do so! Why are they so important? Because of the encapsulation thing. Say what???
Oki, in object oriented programming there is something that we refer to as the three pillars (pillar: something strong that provides defining support), those three pillars are polymorphism, inheritance and encapsulation. The first two I’ll discuss in another post. Encapsulation*” means that a group of related properties, methods, and other members are treated as a single unit or object."*
In other words, to make the code safer we hide implementation details. Kind of you would close the door to the bedroom when you have visitors over, so they wont see that the only reason it is tidy in the livingroom is because all the mess got thrown in the bedroom. Why do they need to see the bedroom anyway? So you close the door, but not for everybody. The person or persons that will have to clean up the mess, or use the room should be allowed to do so.
And how can we remember them: Let me introduce you to the party concept:
The type or member can be accessed by any other code in the same assembly or another assembly that references it.
The type or member can be accessed only by code in the same class or struct.
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
The type or member can be accessed by any code in the same assembly, but not from another assembly.
PROTECTED INTERNAL EDIT : why no image? Because the question was about the different access modifiers, and there are four of them. With them you can set five accessability levels, the fifth level being protected internal.
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.
Do you have a creative way to explain/remember the basic access modifiers? This was the best I could come up with when explaining to a friend that is just getting started with programming. I made up a story about four different parties or events on facebook and what kind of invitations were sent out :D
Last modified on 2012-08-15