Originale-mail to me for new edition

 

Private, protected, and public members

 

A private member is invisible outside of the unit or program where its class is declared. In other words, a private method cannot be called from another module, and a private field or property cannot be read or written to from another module. By placing related class declarations in the same module, you can give the classes access to one another’s private members without making those members more widely accessible.

A protected member is visible anywhere in the module where its class is declared and from any descendant class, regardless of the module where the descendant class appears. In other words, a protected method can be called, and a protected field or property read or written to, from the definition of any method belonging to a class that descends from the one where the protected member is declared. Members that are intended for use only in the implementation of derived classes are usually protected.

A public member is visible wherever its class can be referenced.

 

Topic groups

 

See also

Inheritance and scope

Visibility of class members

 

 

译文

 

私有成员、保护成员和公共成员

 

私有成员在其声明的单元或程序之外是不可见的。也就是说,私有方法不能被另一个模块调用,私有域或属性不能被另一个模块读或写。在同一模块中,通过在一个类声明后放置另一个类的声明,可以实现后者类对前者类中私有成员的访问而不需要将这些私有成员的访问度增加。

保护成员在其声明的模块以及其后裔类声明的模块中都是可见的,而不管其后裔类的声明出现在哪一个模块中。也就是说,在后裔类中任何方法的定义中,都可以调用其祖先类的保护方法、读或写其祖先类的保护域。在起源类实现中仅打算在其后裔类中使用的成员,通常是保护的。

保护成员在其所属的类可以被引用的任何地方都是可见的。

 

主题组

 

相关主题

继承和作用域

类成员的可见度

 

 

编者注

从开发者对源代码的拥有的访问程度来说,类的私有成员、保护成员和公共成员分别具有如下特性:

类的私有成员仅限于对该类具有代码维护能力的开发者可见。例如,单元Unit1的接口部分声明了类Class1,单元Unit2的接口部分或实现部分声明了类Class1的后裔类Class2。那么,类Class2的实现中不能访问类Class1的私有属性。也就是说,如果单元Unit1由开发者A编写完成,而单元Uniit2由开发者B完成,那么开发者A可以以私有成员的方式避免向开发者B提供代码。相反,对于开发者A而言,如果要在单元Unit1中增加其他的引用了Class1的类或者其后裔类,那么类Class1的私有成员在单元Unit1中是可见的。

域私有成员相比,类的保护成员具有相对较高的可见度。这对于代码之间可以互相充分利用资源提供了重要手段。

公共成员的可见度最高,其用途在于为后续开发提供最充分的继承特性。

概括地讲,对于类的成员,应当将那些仅用于当前类实现的成员声明为私有的;可能用于后裔类或引用该类的其他类的成员,应当声明为保护的;那些与当前类的特性密切相关的成员声明为公共的。例如:

 

type

  TMyClass = class(TObject)

  private

    FPosX,

    FPosY: Integer;

    function InternalCal: Integer;

{ 以上成员仅用于当前类的内部使用,因此声明为私有成员。 }

  protected

    procedure Paint; virtual;

{ 上面的过程打算在其后裔类中根据具体情况分别实现,因此声明为保护成员。 }

  public

    procedure MyProc;

    property PosX: Integer read FPosX write FPosX;

    property Width: Integer read InternalCal;

{ 以上成员是当前类被引用时提供的属性和方法,而且它们是创建和使用类的实例(即对象)时重要的接口部分,因此声明为公共属性。 }

  published

    { published详细信息见公布成员 }

  end;