クラス
Delphi でもクラスの開発は可能です。VB ように 1 ファイル、 1 クラスでは無く、ひとつのファイル (ユニット)
内で複数のクラスを記述することが出来ます。
クラスの書き方は構造体に似ています。 ふだん使用している Form もクラスです。
以下のサンプルは "新規作成" でプロジェクトにユニットを追加し作成したクラス TTestClass です。 VBと違って Delphi ではメソッドやプロパティのスコープと実際の処理を分けて記述します。 interface 部で、そのクラスのインターフェイスを、 implementation 部で実際の処理を記述します。
| ■ クラス宣言の例 |
unit Unit2;
interface
uses
Dialogs;
type
TTestClass = class(TObject)
private
FKeyword: string;
public
//初期処理
constructor Create;
//Sayメソッド
procedure Say;
//Keywordプロパティ
property Keyword : string read FKeyword write FKeyword;
end;
implementation
{ TTestClass }
//コンストラクタ
constructor TTestClass.Create;
begin
FKeyword := '';
end;
//Sayメソッド
procedure TTestClass.Say;
begin
ShowMessage(Keyword);
end;
end.
|
constructor は、VBの Class_Initialize と同じで、そのクラスのインスタンス、つまりオブジェクトが生成される際に処理されます。これを
Delphi や他のオブジェクト指向言語ではコンストラクタと呼んでいます。逆に廃棄される際の処理を destructor デストラクタと呼びます。
メソッドは普通の関数や手続きと同じ書き方です。
プロパティの記述は VB とはかなり違います。上記の例では プロパティ「Keyword」は、読みとり、書き込み可能で値は Privateスコープの変数
FKeyword に保存されます。読みとり、書き込みを変数ではなく、関数・手続きで処理したい場合は以下のように記述します。
| ■ クラス宣言の例 |
type
TTestClass = class(TObject)
private
FKeyword: string;
function GetKeyword: string;
procedure SetKeyword(const Value: string);
public
//初期処理
constructor Create;
//Sayメソッド
procedure Say;
//Keywordプロパティ
property Keyword : string read GetKeyword write SetKeyword;
end;
implementation
{ TTestClass }
//コンストラクタ
constructor TTestClass.Create;
begin
FKeyword := '';
end;
//Sayメソッド
procedure TTestClass.Say;
begin
ShowMessage(Keyword);
end;
//Keywordプロパティ (GET)
function TTestClass.GetKeyword: string;
begin
Result := FKeyword;
end;
//Keywordプロパティ (SET)
procedure TTestClass.SetKeyword(const Value: string);
begin
FKeyword := Value;
end;
end.
|
クラス宣言時に使用する TTestClass = class(TObject) の class キーワードの後ろはどのクラスを継承するかを記述します。
TObject は VCL の最も祖先にあたるクラスです。継承クラスを省略した場合は TObject が採用されます。
以下は Unit1 で Unit2に宣言した TTestClass を使用する例です。
| ■ クラス使用の例 |
implementation
{$R *.DFM}
uses
Unit2;
procedure TForm1.Button1Click(Sender: TObject);
var
Test : TTestClass;
begin
Test := TTestClass.Create;
Test.Keyword := 'Hello World';
Test.Say;
Test.Free;
end;
|