Constructors
A constructor is a piece of code that is executed when an object gets created. The constructor usually will to something like setting initial values but may also even perform more complex operations.
A create
statement creates an object by invoking its constructor. Object fields are guaranteed to be initialized to their default values when the constructor is called. If no user-defined default constructor has been implemented, the compiler will implicitly create an empty constructor. This default constructor does nothing.
For class hierarchies, the execution of constructors also follow the given hierarchy: Constructors of parent classes will be executed first, before constructors of child classes get executed. This applies to default constructors as well as to custom constructors.
You can however influence this behavior and replace the implicit call of the parent constructor by an explicit call as described in Calling Constructors of Parent Classes further below.
Declaring a Constructor
You can implement a custom constructor by adding a class operation having the same name as the owning class.
In the example above, both classes Parent and Child contain two custom constructors each (operations marked with orange).
Calling a Constructor
Constructors are called if the name of the created object is followed by parentheses:
Syntax |
| |
---|---|---|
Semantics | Calling a constructor. | |
Substitutables |
| Any given name. |
| Parameters of the constructor. The compiler will invoke a constructor of the class of | |
Examples | Use default constructor:
NONE
Use custom constructor:
NONE
Use custom constructor with specified parameter defined:
NONE
Create local variables using a constructor:
NONE
|
Example
Assume you have this class structure given:
The following table gives an overview on
Statement | Type | Description | Created Object |
---|---|---|---|
| Child | The default constructor of class Child is called. |
JSON
|
| Child | The custom constructor of class Child is called. |
CODE
|
Calling Constructors of Parent Classes
If a constructor needs to call the constructor of its parent class explicitly, you can use the keyword super
. The super()
statement invokes the constructor of the parent class that matches the given parameters.
The super()
statement must be the first statement of the constructor.
Syntax |
| |
---|---|---|
Semantics | Calling a constructor of the parent (super) class. | |
| Parameters of the constructor. The compiler will then invoke a constructor of the parent class having the same parameters. | |
Examples |
NONE
|
Related Pages:
Basics of the Action Script Language: