As an alternative to class types,
you can declare object types using the syntax
type objectTypeName =
object (ancestorObjectType)
memberList
end;
where objectTypeName is any valid
identifier, (ancestorObjectType) is optional, and memberList
declares fields, methods, and properties. If (ancestorObjectType) is
omitted, then the new type has no ancestor. Object types cannot have published
members.
Since object types do not descend
from TObject, they provide no built-in constructors, destructors, or
other methods. You can create instances of an object type using the New
procedure and destroy them with the Dispose procedure, or you can simply
declare variables of an object type, just as you would with records.
Object types are supported for backward compatibility only. Their use is not recommended.
与类类型处于并列范畴的是对象类型,声明对象类型可以使用如下语法:
type objectTypeName =
object (ancestorObjectType)
memberList
end;
这里的对象类型名称objectTypeName是任意有效的标识符,祖先对象类型
(ancestorObjectType) 是可选的,成员列表memberList声明了域、方法和属性。如果祖先对象类型(ancestorObjectType)被忽略,那么新的类型没有祖先。对象类型不能(象类类型那样)公布成员。
由于对象类型不是遗传自TObject,所以不提供内建的构造器、析构器或其他成员。可以用New过程和Dispose创建和销毁对象类型的实例,或者就象声明记录一样简单地声明对象类型变量。
对象类型仅提供向后(旧版本)的兼容性,因此不推荐使用。
编者注
对象类型是较早Pascal语言版本(最早出现于Turbo Pascal,也是Borland公司的代表产品)中面向对象技术的体现形式。下面的例子简单说明了对象类型的声明、对象类型实例(即对象)的声明和使用(仅作为回顾以前的面向对象技术参考,因为新的版本所提供的类类型解决方案更严谨、完善):
type
ObjA = object
private
protected
public
procedure DoSomething;
procedure DoNext;
// published//对象类型不能公布成员
end;
ObjB = object(ObjA)//继承自ObjA
public
procedure DoSomething;
end;
//象记录指针类型那样声明对象类型指针
PObjA = ^ObjA;
PObjB = ^ObjB;
procedure
ObjA.DoSomething;
begin
MessageBox(0, 'Object types (ObjA)', 'OK', ID_OK);
end;
procedure
ObjA.DoNext;
begin
MessageBox(0, 'Next (ObjA)', 'OK', ID_OK);
end;
procedure
ObjB.DoSomething;
begin
inherited;//这将导致调用ObjA中的同名方法
MessageBox(0, 'Object types (ObjB)', 'OK', ID_OK);
end;
var
P: PObjA;//对象类型指针,指向ObjA类型的实例,这类指针的使用和普通类型指针一样
A: ObjB;//直接象一般类型那样声明对象实例,声明时会自动为其分配内存,其内存的释放也自动完成
...
begin
...
New(P);//创建对象实例
P^.DoSomething;//调用方法,也可以简单写成 P.DoSomething;
A.DoSomething;//直接调用方法,对象实例已经在变量A声明时自动创建
Dispose(P);//销毁对象实例
...
end;