Given a class definition, Java provides a mechanism called new for creating new instances of the class. To exploit the new construct, 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 the return type in the heading. The constructor for our sample class Entry has the following form:
Entry(String n, String a, String p) { this.name = n; this.address = a; this.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(, , ), , 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.
Finger Exercise: Add a second constructor to your saved Entry class. Your second constructor should take one argument, the
value of String name, and initialize the other fields to the
String "unknown". Test your code.