Java Reference
In-Depth Information
constructor has no return type. Instead, an instance of the class type itself is
returned. Except for some special situations discussed later, the only way to
invoke a constructor is with the new operator. The constructor's name must
exactly match the class name, including case.
Constructors are useful for initializing variables and invoking any methods
needed for initialization. The code here shows a simple class with a constructor
and one method.
class Test
{
int i;
Test (int j) {
i = j;
A constructor is called when an
instance of this class is first
created. Here it is used to
initialize a property variable .
}
int get () {
return i;
}
}
The above code for the constructor,
Test (int j) {
i = j;
}
shows that in the process of creating an instance of the class, an initial value for
the member variable i is passed as a parameter to the constructor.
Java does not actually require an explicit constructor in the class descrip-
tion. If you do not include a constructor, the Java compiler creates a default
constructor in the bytecode with an empty parameter list. The default con-
structor for a class Test with no constructor is equivalent to explicitly
writing
Test () {/* do nothing */}
In the discussion of data fields, we noted that the data can receive explicit ini-
tial values or default values. You might wonder when this initialization actually
occurs. The javac compiler, in fact, inserts the initialization of the data into the
bytecode for the constructor. So, for instance, if the Test class had no explicit
constructor, the bytecode would be equivalent to that shown below where a con-
structor explicitly sets the int variable to 0:
 
Search WWH ::




Custom Search