Name

Protected Directive

Syntax

type Class declaration
protected
   Field declarations...
   Method and property declarations...
end;

Description

The protected directive introduces the protected section of a class declaration. Protected fields, methods, and properties are accessible only by methods of the class and its descendants. Classes and subroutines declared in the same unit can also access the protected declarations.

Tips and Tricks

  • Most methods or properties that are not part of the public interface should usually be made protected. When you declare a method as private, or do not have a protected property to access a private field, you are limiting the ways your class can be reused. You cannot predict the ways in which a class will be used in other projects, and hiding important declarations in a private section only frustrates would-be users of your class.

  • On the other hand, details of the implementation of a class must sometimes be kept private so you can be free to change the implementation in a future revision. Be sure to define appropriate protected methods to allow reuse of your class, even if the protected method merely calls a private method.

  • Many protected methods should be virtual. Because it is difficult to know how a subclass might want to extend or alter the behavior of an ancestor class, it is usually better to err on the side of too much flexibility. Make a protected method static only when you have a reason to do so.

Example

See the class keyword for an example.

See ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.