A class definition typically includes one or more fields that declare
data of various types. For example, this code shows a class with
a single int
datum:
public
class
GenericClass
{
int x = 0;
public int getX
()
{
return x;
}
public void setX
(int i)
{
x = i;
}
}
|
Field with a declaration of an integer data variable. This
instance variable is accessible to all methods in the class.
A method to obtain the value of the x variable.
A method to set the value of the x variable.
|
This data is accessible to all the methods
in the class. Here, for example, the getX()
method returns the value in the x variable and the setX(int
i) method sets x to the value passed in the method argument.
When the data field declaration does not assign an explicit value
to the data, default values will be used:
- int, byte,
short, char - default value
0
- float, double
- default value
0.0
- boolean -
default value
false
public
class
GenericClass
{
int i;
double d = 1.3;
boolean b = true;
...
}
|
Fields can use either the default values or explicit initialization
|
We mentioned in Chapter 2 identifer
rules for naming field data: identifiers cannot begin with a
number and cannot contain a punctuation character or any character
listed in the Reserved
Symbols Table. Underscore _ and the dollar sign $ are allowed.
Latest update: Oct. 17, 2004
|