When declaring a field earlier in the chapter, you prefixed the field declaration with the keyword public. public is an access modifier that identifies the level of encapsulation associated with the member it decorates. Five access modifiers are available: public, private, protected, internal, and protected internal. This section considers the first two.
The purpose of an access modifier is to provide encapsulation. By using public, you explicitly indicated that it is acceptable that the modified fields are accessible from outside the Employee classin other words, that they are accessible from the Program class, for example. Consider an Employee class that includes a Password field, however. It should be possible to call an Employee object and verify the password using a Logon() method. It should not be possible, however, to access the Password field on an Employee object from outside the class. To define a Password field as hidden and inaccessible from outside the containing class, you use the keyword private for the access modifier, in place of public (see Listing 5.15). As a result, the Password field is not intended for access from inside the Program class, for example. Listing 5.15. Using the private Access Modifier
Although not shown in Listing 5.15, it is possible to decorate a method with an access modifier of private as well. Note that if no access modifier is placed on a class member, the declaration will default to private. In other words, members are private by default and programmers need to specify explicitly that a member is to be public. |