Skip to content
Delphi

Units and Classes

Define units with interface and implementation sections.

By EZ4Code Team
unitclassoop

Code

unit MyUnit;

interface

type
  TPerson = class
  private
    FName: string;
    FAge: Integer;
  public
    constructor Create(const Name: string; Age: Integer);
    destructor Destroy; override;
    property Name: string read FName write FName;
    property Age: Integer read FAge write FAge;
    function ToString: string; override;
  end;

implementation

constructor TPerson.Create(const Name: string; Age: Integer);
begin
  inherited Create;
  FName := Name;
  FAge := Age;
end;

destructor TPerson.Destroy;
begin
  // cleanup
  inherited;
end;

function TPerson.ToString: string;
begin
  Result := Format('%s (%d)', [FName, FAge]);
end;

end.

Explanation

Delphi units have interface (public) and implementation sections. Classes use TFoo convention. Properties expose fields with read/write specifiers. inherited calls the parent method — always call inherited Create first and inherited Destroy last. Use Free instead of direct Destroy for safety.

More Delphi Snippets