Java Reference
In-Depth Information
public double circumference () { // Compute the circumference
// of the circle
return 2 * PI * r ;
}
}
It is not normally good practice to have a public field r
instead, it would be much more usual to have a private field
r and a method radius() to provide access to it. The rea‐
son for this will be explained later, in “Data Hiding and
Encapsulation” on page 121 . For now, we use a public field
simply to give examples of how to work with instance
fields.
m
g
O
The following sections explain all four common kinds of members. First, we cover
the declaration syntax for fields. (The syntax for declaring methods is covered later
in this chapter in “Data Hiding and Encapsulation” on page 121 .)
Field Declaration Syntax
Field declaration syntax is much like the syntax for declaring local variables (see
Chapter 2 ) except that field definitions may also include modifiers. The simplest
field declaration consists of the field type followed by the field name. The type may
be preceded by zero or more modifier keywords or annotations, and the name may
be followed by an equals sign and initializer expression that provides the initial
value of the field. If two or more fields share the same type and modifiers, the type
may be followed by a comma-separated list of field names and initializers. Here are
some valid field declarations:
int x = 1 ;
private String name ;
public static final int DAYS_PER_WEEK = 7 ;
String [] daynames = new String [ DAYS_PER_WEEK ];
private int a = 17 , b = 37 , c = 53 ;
Field modifiers are comprised of zero or more of the following keywords:
public , protected , private
These access modifiers specify whether and where a field can be used outside of
the class that defines it.
static
If present, this modifier specifies that the field is associated with the defining
class itself rather than with each instance of the class.
fina This modifier specifies that once the field has been initialized, its value may
never be changed. Fields that are both static and final are compile-time
Search WWH ::




Custom Search