Last Updated:

Object Properties in Delphi

In Object Pascal, restricting access to an object's fields is implemented by using the object's properties. An object property is characterized by a field that stores the property value and two methods that provide access to the property field.

The method of setting the value of a property is called the method of writing a property (write), the method of obtaining the value of the property is called the method of reading the property (read).

In the class description, the name of the property is preceded by the word property. The property name is followed by its type, followed by the names of the methods that provide access to the property value.

The word read is followed by the name of the method that reads the property, followed by the name of the property's write method. The following example describes a class with two properties, Name and Oklad.

Tperson=class
private
fname:string;
foklad:integer;
Constructor Create(name:string; oklad: integer);
Procedure show;
Function GetName : string;
Function GetOklad : integer;
Procedure SetOklad (NewOklad:integer);
public
Property Name:string
read GetName;
Property Oklad: integer
read GetOklad
write SetOklad;
end;

You do not have to write an instruction to set a property to an object to set a property value, you can write a regular property value statement. For example, to assign a value to the Oklad property of the sotrudnik object, it is sufficient to write

sotrudnik. Oklad:=300;

The compiler translates the instruction into a method call instruction

sotrudnik. SetOklad(300);

Externally, using properties in a program is no different from using object fields. However, there is a fundamental difference between a property and an object field: when a property value is assigned and read, a procedure is automatically called that performs some actions.

In your program, you can assign some additional tasks to property methods. For example, you can use a method to check the correctness of the values assigned to a property, set the values of other fields logically related to the property, and call a helper procedure.

Making object data as properties allows you to restrict access to fields that store object property values, for example, you can allow read-only.

To prevent program statements from changing the value of the property, you must specify only the name of the read method. Attempting to assign values to a read-only property will cause a compilation error. In the class description above, the Name property is read-only and the Oklad property is read/write.

You can set the value of a write-protected property during object initialization.