Unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end;There are only two fields in the TMyClass1 class (the variable comes to the class to be called the field) TMyClass1 = class
FName: string; {字段命名一般用 F 开头, 应该是取 field 的首字母}
FAge: Integer; {另外: 类的字段必须在方法和属性前面}
end;
{这个类中的两个字段, 可以随便读写; 在实际运用中, 这种情况是不存在的.} //tmyclass2 class contains two properties (property), two methods, two and TMyClass1 the same fields TMyClass2 = class
strict private
FName: string;
FAge: Integer;
procedure SetAge(const Value: Integer);
procedure SetName(const Value: string);
published
property Name: string read FName write SetName;
property Age: Integer read FAge write SetAge;
end;
{
But here's the fields: FName, Fage and methods: Setage, SetName is not accessible,
Because they are encapsulated in the strict private area, they can only be used inside the class after encapsulation.
There are three elements in the attribute:
1. Specify the data type: For example, the age attribute is an Integer type;
2, how to read: For example, read the age attribute, actually read the Fage field;
3, how to write: such as Hill age attribute, is actually through the Setage method.
Property is just a bridge.
What is the difference between a property access field and a direct access field?
By attributes can give access to a certain limit,
For example: A person's age can not be more than 200 years old, and will not be negative; A person's name should not be a null value.
This limitation is increased by looking at the implementation of the two methods of the TMyClass2 class in the implementation area.
}
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyClass2 }
procedure TMyClass2.SetAge(const Value: Integer);
begin
if (Value>=0) and (Value<200) then
FAge := Value;
end;
procedure TMyClass2.SetName(const Value: string);
begin
if Value<>'' then
FName := Value;
end;
Test:
procedure TForm1.Button1Click(Sender: TObject);
var
class1: TMyClass1;
class2: TMyClass2;
begin
class1 := TMyClass1.Create;
class2 := TMyClass2.Create;
class1.FAge := 1000; {TMyClass1 中的 FAge 字段可以接受一个离奇的年龄}
class2.Age := 99; {通过 TMyClass2 中的 Age 属性, 只能赋一个合理的值}
//class2.FAge := 99; {TMyClass2 中的 FAge 字段被封装了, 在这里无法使用}
class1.Free;
class2.Free;
end;
End.