Information Technology Reference
In-Depth Information
Access Modifiers
From within a class, any function member can access any other member of the class simply by
using that member's name.
The
access modifier
is an optional part of a member declaration that specifies what other
parts of the program have access to the member. The access modifier is placed before the sim-
ple declaration forms shown previously. The following is the syntax for fields and methods:
Fields
AccessModifier
Type
Identifier;
Methods
AccessModifier
ReturnType
MethodName
()
{
...
}
The five categories of member access are the following. I will describe the first two in this
chapter, and the others in Chapter 7.
• private
• public
• protected
• internal
protected internal
Private and Public Access
Private members are only accessible from within the class in which they are declared—other
classes cannot see or access them.
Private access is the default access level—so if a member is declared without an access
modifier, it is a private member.
You can also use the
private
access modifier to explicitly declare a member private.
There is no semantic difference between declaring a private member implicitly as
opposed to explicitly. They act exactly the same.
For example, the following two declarations both specify
private
int
members:
int MyInt1; // Implicitly declared private
private int MyInt2; // Explicitly declared private
↑
Access modifier