Here I am with the second tip for the Delphi Developer Certification and it’s about constructor.
Every Delphi Developer should know that every single class has a Constructor method, which is used to create the object. The RAD Studio documentation describe the Constructor as:
A constructor is a special method that creates and initializes instance objects. The declaration of a constructor looks like a procedure declaration, but it begins with the word constructor.
It is conventional to call the constructor Create, a class can have more than one constructor, but most of the time we just see one. Since what define the class constructor is the keyword constructor, you can call it whatever you want. There are many situations where you will need multiple constructors, in general we don’t use multiples names, but the capability to give different names for the constructor could help to have a better understating of the code. The following example has 7 different constructors using three different names Create, New and Update:
TMyClass = class public name : string; constructor Create; overload; // This constructor uses defaults constructor Create(name : string); overload; constructor Create(name : string; age : Integer); overload; constructor New(name : string);overload; constructor New(name : string; age : Integer);overload; constructor Update(name : string);overload; constructor Update(name : string; age : Integer);overload;
The TMyClass could be instantiated using one of the following constructor: TMyClass.Create; TMyClass.Create('Mike'); TMyClass.Create('Mike', 50); TMyClass.New('Mike'); TMyClass.New('Mike', 50); TMyClass.Update('Mike'); TMyClass.Update('Mike', 30);
There are more to learn about Constructors and I suggest the following links: