The code then makes a block of code surrounded by braces. It declares the variable i and displays
its value. Note that the code could not create a second variable named
count inside this block
because the higher-level method code contains a variable with that name.
After the first block ends, the code creates a second block. It makes a new variable
i within that
block and displays its value. Because the two inner blocks are not nested (neither contains the other),
it’s okay for both blocks to define variables named
i.
ACCESSIBILITY
A field’s scope determines what parts of the code can see the variable. So far I’ve focused on the fact
that all of the code in a class can see a field declared at the class level, outside of any methods. In
fact, a field may also be visible to code running in other classes depending on its accessibility.
A field’s accessibility determines which code is allowed to access the field. For example, a class
might contain a public field that is visible to the code in any other class. It may also define a private
field that is visible only to code within the class that defines it.
Accessibility is not the same as scope, but the two work closely together to determine what code can
access a field.
Table 13-1 summarizes the field accessibility values. Later when you learn how to build properties and
methods, you’ll be able to use the same accessibility values to determine what code can access them.
TABLE 131
ACCESSIBILITY VALUE MEANING
public
Any code can see the variable.
private
Only code in the same class can see the variable.
protected
Only code in the same class or a derived class can see the variable.
For example, if the
Manager class is derived from the Person class,
a
Manager object can see a Person object’s protected variables.
(You’ll learn more about deriving one class from another in Lesson 23.)
internal
Only code in the same assembly can see the variable. For example, if
the variable’s class is contained in a library (which is its own assembly),
a main program that uses the library cannot see the variable.
protected internal
The variable is visible to any code in the same assembly or any derived
class in another assembly.
If you omit the accessibility value for a field, it defaults to private. You can still include the private
keyword, however, to make the field’s accessibility obvious.
The
private keyword sometimes causes confusion. A private field is visible to any code in any
instance of the same class, not just to the same instance of the class.
596906c13.indd 167 4/7/10 12:32:48 PM