next up previous
Next: 1.4.3 Defining Instance Methods Up: 1.4 Java Class Definitions Previous: 1.4.1 Defining Classes to

1.4.2 Constructors

If we use define-struct to define a new form of Scheme data named Entry with three fields, Scheme generates a procedure make-Entry of three arguments that constructs a new instance of the structure containing the field values specified by the arguments. Java provides a similar mechanism called new for creating new instances of a class, but the class must provide a special method called a constructor that specifies how the fields are initialized. A constructor method has the same name as the class and does not contain either a return type or the modifier static in the heading. The constructor for our sample class Entry has the following form:

  Entry(String n, String a, String p) {
    name = n;
    address = a;
    phone = p;
Like a method with void return type, a constructor does not contain a return statement.

If the preceding constructor is included in the definition of class Entry, then the expression

  new Entry("Corky", "DH 3104", "x 6042")
constructs an instance of class Entry with the name "Corky", the address "DH 3104", and the phone "x 6042". The value of the new expression is the created object.

In general, a class may have several different constructors, but each constructor must have a distinct list of argument types (so the Java compiler can determine which one is meant!). If a class does not include a constructor, Java generates a default constructor of no arguments that initializes each field of the object to the ``null'' value of its declared type. The ``null'' value for any class type is the value null, which refers to nothing. The null value of each primitive type is the ``zero'' value for that type: 0 for the six numeric primitive types, false for boolean, and the null character (which has code 0) for char.

Let us summarize syntax for constructors. A constructor definition for a class C begins with name of the class followed by a (possibly empty) list of parameters separated by commas and enclosed in parentheses. The remainder of the constructor definition is a (possibly empty) sequence of Java statements enclosed in braces. When a new instance of class C is created, the body of the corresponding constructor is executed to initialize the fields of the created object. New objects are created by new expressions that have the form

new C(E1, $\dots$, En)
E1, $\dots$, En are expressions with types matching the parameter declarations for some constructor of class C. When a new expression is evaluated, Java creates a new instance of class C and initializes the fields of C by binding the parameters of the matching constructor to the values of the argument expressions and executing the statements in the body of the constructor.

next up previous
Next: 1.4.3 Defining Instance Methods Up: 1.4 Java Class Definitions Previous: 1.4.1 Defining Classes to
Corky Cartwright