Java Reference
In-Depth Information
The following statement needs some explanation:
// Increase count by one
Human.count++;
It uses the increment operator (++) on the
count
class variable. After the
count
class variable is incremented by 1,
you read and print its value. The output shows that after incrementing its value by
1
, its value becomes
1
. It means that
its value was zero before the
Human.count++
statement was executed. However, you have never set its value to zero. Its
declaration was as follows:
static long count;
When the
count
class variable was declared as shown above, it was initialized to zero by default. All fields of a
class (class variables and instance variables) are initialized to a default value, if you do not assign an initial value to
them. I will discuss the initialization of fields of a class in detail in the next section.
Default Initialization of Fields
All fields of a class, static as well as non-static, are initialized to a default value. The default value of a field depends on
its data type.
•
A numeric field (
byte
,
short
,
char
,
int
,
long
,
float
, and
double
) is initialized to zero.
•
A
boolean
field is initialized to
false
.
A reference type field is initialized to
null
.
According to the above rules, the fields of the
Human
class will be initialized as follows:
The
•
•
count
class variable is initialized to zero because it is of numeric type. This is the reason,
Human.count++
evaluated to
1
(
0 + 1 = 1
) as shown in the output of Listing 6-2.
The
name
and
gender
instance variables are of
String
type. String is a reference type. They are
initialized to
null
. Recall that a copy of the
name
and
gender
fields exists for every object of the
Human
class, and each copy of
name
and
gender
is initialized to
null
.
If you consider the above default initialization of the fields of the
Human
class, it behaves as if you have declared
the
Human
class as shown below. This declaration of the
Human
class and the one as shown in Listing 6-1 are the same.
•
class Human {
String name = null;
String gender = null;
static long count = 0;
}
Listing 6-3 demonstrates the default initialization of fields. The
DefaultInit
class includes only instance
variables. The class fields are initialized with the same default value as the instance fields. If you declare all fields of
the
DefaultInit
class as
static
, the output will be the same.