Wednesday, October 27, 2010

The Constructor - New()

A constructor is represented on a class diagram as: Visibility New(ParametersIfAny) and is always the first behavior in the list.

A constructor behavior may require parameters to execute. This solely depends on the requirements of the system and the design of the object. Parameters are required if it makes sense that the object should know something about its state upon creation.

For instance, an object created from the Player class would not make much sense if it's Name state did not have a value. The account status of the object may also be very important to establish. In the diagram below, you will notice that the constructor for the Player object contains a number of parameters.
+New(NewName: String, NewHealth: Integer, AccountStatus: Boolean, NewPassword: String)

As the designer of the class, I have decided that a Player object would not make sense unless all of the states were established at the time of object instantiation, however, the Sword and Flight class do not require any parameters for object instantiation.


Note: A constructor behavior cannot return a value, therefore it is always implemented as a subroutine.

No comments:

Post a Comment