类与对象的基础概念
在Delphi中,面向对象编程(OOP)是一种核心编程范式。它允许开发者将数据(属性)和行为(方法)封装在单个实体中,即“对象”。类是对象的蓝图或模板,它定义了对象可以具有的属性和方法。
类的定义
type
TPerson = class
private
FName: string;
FAge: Integer;
public
property Name: string read FName write FName;
property Age: Integer read FAge write FAge;
procedure Display;
end;
在这个例子中,TPerson 类有两个私有属性:FName 和 FAge。它们通过公共属性 Name 和 Age 访问。Display 方法用于显示个人信息。
创建对象
var
Person1: TPerson;
begin
Person1 := TPerson.Create;
try
Person1.Name := 'Alice';
Person1.Age := 30;
Person1.Display;
finally
Person1.Free;
end;
end;
这里,我们创建了一个 TPerson 类的实例 Person1,设置其属性,并调用 Display 方法。
继承与多态
继承是OOP中的另一个重要概念,它允许创建新的类(子类)基于现有类(父类)的定义。多态则允许使用基类类型的变量来处理子类对象。
继承的例子
type
TEmployee = class(TPerson)
private
FEmployeeID: Integer;
public
property EmployeeID: Integer read FEmployeeID write FEmployeeID;
constructor Create(AName: string; AAge: Integer; AnEmployeeID: Integer);
end;
constructor TEmployee.Create(AName: string; AAge: Integer; AnEmployeeID: Integer);
begin
inherited Create(AName, AAge);
FEmployeeID := AnEmployeeID;
end;
在这个例子中,TEmployee 类继承自 TPerson 类,并添加了一个新的属性 EmployeeID。
多态的例子
var
People: array of TPerson;
begin
SetLength(People, 2);
People[0] := TPerson.Create('Alice', 30);
People[1] := TEmployee.Create('Bob', 25, 12345);
for i := Low(People) to High(People) do
People[i].Display;
end;
在这个例子中,我们有一个 TPerson 类的数组 People,它包含 TPerson 和 TEmployee 类的对象。通过基类引用调用 Display 方法,即使对象是子类的实例。
实战案例:制作一个简单的待办事项列表
在这个实战案例中,我们将创建一个待办事项列表,它将允许用户添加、删除和显示待办事项。
类的设计
type
TTodoItem = class
private
FDescription: string;
FCompleted: Boolean;
public
property Description: string read FDescription write FDescription;
property Completed: Boolean read FCompleted write FCompleted;
constructor Create(ADescription: string);
procedure MarkAsCompleted;
end;
TTodoList = class
private
FItems: TStringList;
public
constructor Create;
destructor Destroy; override;
procedure AddItem(AItem: string);
procedure RemoveItem(AIndex: Integer);
procedure DisplayItems;
end;
源码解析
TTodoItem类代表一个待办事项,具有描述和完成状态。TTodoList类管理待办事项列表,提供添加、删除和显示功能。
使用示例
var
TodoList: TTodoList;
Item: TTodoItem;
begin
TodoList := TTodoList.Create;
try
Item := TTodoItem.Create('Buy milk');
TodoList.AddItem(Item.Description);
Item.Free;
Item := TTodoItem.Create('Read book');
TodoList.AddItem(Item.Description);
Item.Free;
TodoList.DisplayItems;
TodoList.RemoveItem(0);
TodoList.DisplayItems;
finally
TodoList.Free;
end;
end;
在这个例子中,我们创建了一个 TTodoList 实例,添加了两个待办事项,然后显示了它们。之后,我们删除了第一个待办事项,并再次显示了列表。
通过这个案例,你将了解到如何在Delphi中使用面向对象编程来创建实用的应用程序。随着经验的积累,你可以进一步扩展这个案例,增加更多功能,如数据持久化、用户界面等。
