Earlier in this tutorial they considered the use of constructors & of method overloading. In this article they will combine these three techniques to permit some of constructors to be defined for a single class. This gives the class the flexibility to construct objects in a variety of ways according to the manner in which they are to be used.
Creating Overloaded Constructors
Creating an overloaded constructor is as simple as adding overloaded methods. Additional builders simply added to the code. Each manufacturer must have a unique signature, ie. parameter types must be different from all other builders.
To demonstrate the use of overloaded constructors they will generate a new class to represent rectangular shapes. The class will permit the generation of a Rectangle object with specified Height and Width properties. They will then add a second constructor that requires only a single parameter for square shapes with matching height and width.
To start, generate a new console application and add a new class file named "Rectangle". Add the following code to the new class to generate the properties:
class Rectangle
- {
- private int _height;
- private int _width;
- public int Height
- {
- get
- {
- return _height;
- }
- }
- public int Width
- {
- get
- {
- return _width;
- }
- }
- }
Constructor Interaction
Builders can be very complex, performing many functions for initialisation and validation of new objects. This can easily lead to large developers with functionality that is repeated in each overloaded version. This, in turn, can lead to maintenance problems with the code when changes are required to the logic of the construction. This can be minimized by having methods called in the constructor of the class to perform common tasks. Another option is to allow code reuse by making the constructors call each other during object instantiation.
To generate a constructor that calls an existing constructor, a special syntax is used. The constructor is declared as usual & then a colon character (:) is appended. After the colon the this keyword & the parameter list of the called constructor is provided. Each parameter specified in the call must match two of those in the new constructor or be a literal value.
public Constructor(parameters-1) : this(parameters-2)
{
}
0 comments:
Post a Comment