Java Reference
In-Depth Information
public class
GenericClass
{
int i = 12;
Field with a declaration of
an integer data variable
.
public int get () {
A method to obtain the value
of the i variable
.
return i;
}
}
Methods (discussed later) can access the data in the fields. Here, for example, the
get()
method returns the value in the
i
field.
When a data field declaration does not assign an explicit value to the data,
default values are assigned:
int
,
byte
,
short
,
char
- default value
0
float
,
double
- default value
0.0
boolean
- default value
false
In the following example, we let one variable take a default value and set explicit
values for two of the variables. Setting an explicit value, even if it is the same as
the default, can be a good practice just to confirm that every field has the initial
value that you intended for it.
public class
GenericClass
{
Fields can use either the
default values or explicit
initialization.
Here i will holda0value
.
int i;
double d
=
1.3;
boolean b
=
true;
...
}
The fields can reside anywhere in the class definition (outside of methods) but
putting them all at the top (before the methods) is a popular coding style that we
follow.
3.3.2 Methods
A class definition typically includes one or more
methods
that carry out some
action with the data and may or may not return a value. The following code shows
a class with two methods -
get()
and
triple()
- that return the value of an
integer datum and one method -
set()
- that does not return a value (
void
):
Search WWH ::
Custom Search