Java Reference
In-Depth Information
Constructor -Aspecial kind of method called when an object is created. Its job is to
carry out initialization tasks.
The class GenericClass below illustrates these features:
public class GenericClass
{
int i;
This field declares the
property i as an integer
type. (By default its
value will be 0.)
public GenericClass (int j) {
i = j;
A constructor is called
when an instance of this
class is first created.
It can be used to
initialize properties .
}
public void set (int j) (
This method assigns a
value to the field i .
i = j;
}
public int get () {
This method returns the
value of i .
return i;
}
}
We can now create an instance of our new data type and invoke its methods:
void aMethodSomewhere () {
// Create an instance of this data type.
GenericClass g = new GenericClass (5);
int k = g.get ();
...
In the following pages we discuss the main features of a class definition, beginning
with data fields.
3.3.1 Data fields
A class definition typically includes one or more fields that declare data of various
types. Data fields are also called “member variables.” For example, this code
shows a class with a single primitive int data value:
 
Search WWH ::




Custom Search