RAD Studio |  |

Scope and Qualifiers
See Also
Collapse All

Scope determines the accessibility of an object's fields, properties, and methods. All members declared in a class are available to that class and, as is discussed later, often to its descendants. Although a method's implementation code appears outside of the class declaration, the method is still within the scope of the class because it is declared in the class declaration.

When you write code to implement a method that refers to properties, methods, or fields of the class where the method is declared, you don't need to preface those identifiers with the name of the class. For example, if you put a button on a new form, you could write this event handler for the button's OnClick event:

Copy Code

    procedure TForm1.Button1Click(Sender: TObject);
    begin
      Color := clFuchsia;
      Button1.Color := clLime;
    end;

The first statement is equivalent to

Copy Code

    Form1.Color := clFuchsia

You don't need to qualify Color with Form1 because the Button1Click method is part of TForm1; identifiers in the method body therefore fall within the scope of the TForm1 instance where the method is called. The second statement, in contrast, refers to the color of the button object (not of the form where the event handler is declared), so it requires qualification.

The IDE creates a separate unit (source code) file for each form. If you want to access one form's components from another form's unit file, you need to qualify the component names, like this:

Copy Code

    Form2.Edit1.Color := clLime;

In the same way, you can access a component's methods from another form. For example,

Copy Code

    Form2.Edit1.Clear;

To access Form2's components from Form1's unit file, you must also add Form2's unit to the uses clause of Form1's unit.

The scope of a class extends to its descendants. You can, however, redeclare a field, property, or method in a descendant class. Such redeclarations either hide or override the inherited member.

See Also

Object Pascal and the Class Libraries

Properties

Private

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!