Java Reference
In-Depth Information
Java syntax: constructor declaration
public class-name ( parameter-declarations ) {
sequence of statements and declarations
Purpose : To define a constructor in class class-name , declare its parame-
ters, and give the sequence of statements to execute when the constructor is
called. Each parameter declaration has the form type variable , and adjacent
parameter declarations are separated by commas. The purpose of a con-
structor call is to initialize the fields of a newly created folder.
A constructor is called when an instance is first created —we see how this
is done in Sec. 3.2. The purpose of a constructor is to initialize the fields of the
newly created instance . That is all. In the constructor shown above, field name is
initialized to parameter n and field start to parameter d . Field salary need not
be assigned because the initialization appears in its declaration.
How does one distinguish a constructor from a procedure or function? A pro-
cedure has keyword void just before the procedure name in its declaration. A
function has the return type in this place. A constructor has neither. Furthermore,
the constructor name must be the same as the class in which it is declared.
Note carefully the specification of the constructor. In this text, all construc-
tor specifications have the form “Constructor: an instance with ...”, where we
state exactly what value each field is initialized to, mentioning the parameters
where necessary. Please use this convention for your constructor specifications.
Style Note
spec for a
The default constructor
If no constructor is declared in a class C (say), Java declares this one for you
(but it does not appear explicitly in the class definition):
/** Constructor: an instance with initialization as given in
the field declarations */
public C() { }
Thus, if you can give the initial values of the fields in their declarations,
there is no need to write a constructor.
If you do define a constructor in a class, the default constructor is not placed
in the class by Java. So, if you want two constructors, one of which is the default,
you have to explicitly define the constructor shown above in the class.
The use of several constructors
The constructor in class Employee has two parameters, the name and hire
date. Most people for whom an instance will be created will be new hires, so the
year will be the year in which the instance is created. To save users effort, we can
write a second constructor that has only the name of the person, with the hire date
being the current year. Such a constructor is presented below.
Search WWH ::

Custom Search