A constructor is a special function that creates an instance of the class that it’s associated with. It can be used to set initial values for the new object.
|
Defining a constructor for a class: You can add a constructor for a class by adding the <constructor> specifier on the function name. Instead of specifying a return type on the function, the function is assigned the class name followed by any initialization of fields. A class can have more than one constructor. |
|
Adding variables and executing code in the constructor: You can execute expressions within a constructor with the block expression, and introduce new variables with the keyword let . |
|
Calling other constructors in a constructor: You can call other constructors from a constructor. You can also call constructors for the superclass of the class from a constructor of the class as long as all fields are initialized. When a constructor calls another constructor and both constructors initialize fields, only the values provided to the first constructor are used for the fields. The order of evaluation for expressions between the two constructors will be in the order the expressions are written (as far as side effects are concerned), but only the values provided to the first constructor are used. |