C Sharp Programming/Encapsulation
From Wikibooks, the open-content textbooks collection
Cover | Introduction | Basics | Classes | The .NET Framework | Advanced Topics | Index
Encapsulation is depriving of the user of a class information he does not need, and preventing him from manipulating objects in ways not intended by the designer.
A class element having public protection level is accessible to all code anywhere in the program. These methods and properties represent the operations allowed on the class to outside users.
Methods, data members (and other elements) with private protection level represent the internal state of the class (for variables), and operations which are not allowed to outside users.
For example:
public class Frog
{
public void JumpLow() { Jump(1); }
public void JumpHigh() { Jump(10); }
private void Jump(int height) { _height += height;}
private int _height = 0;
}
In this example, the public method the Frog class exposes are JumpLow and JumpHigh. Internally, they are implemented using the private Jump function that can jump to any height. This operation is not visible to an outside user, so he cannot make the frog jump 100 meters, only 10 or 1. The Jump private method is implemented by changing the value of a private data member _height, which is also not visible to an outside user. Some private data members are made visible by Properties.
Contents |
[edit] Protection Levels
[edit] Private
Private members are only accessible within the class itself. A method in another class, even a class derived from the class with private members cannot access the members.
[edit] Protected
Protected members can be accessed by the class itself and by any class derived from that class.
[edit] Public
Public members can be accessed by any method in any class.
[edit] Internal
Internal members are accessible only in the same assembly and invisible outside it.


