What are normal and static fields in Pascal classes?
Classes are used in Pascal. Classes are defined similarly to objects. However, classes are not objects but blueprints or templates for creating objects.
Classes include fields, properties, and methods. Depending on their definition, fields can hold data specific to an instance or the whole class.
Typically, fields are categorized into two types:
Normal fields: Normal fields refer to variables local to each class instance.
Static fields: Static fields or class variables are global to the class and act similarly to global variables. These variables maintain their values between calls and can reference within the class's methods. Also, it is possible to refer to them by providing a fully qualified name.
Let's go through the following examples to better understand the distinction between these two types of fields:
Normal fields
This example illustrates working with normal fields whose values are local to each class instance.
program hello;{$mode objfpc}typemyClass = classv : integer;end;varcl1,cl2 : myClass;beginwriteln('Start...');cl1:=myClass.create;cl2:=myClass.create;cl1.v:=5;cl2.v:=10;writeln('cl1.v=',cl1.v,' cl2.v=',cl2.v);writeln('End...');end.
Code explanation
Let's explain the code widget above:
Line 1: We refer to the program header. Used for backward compatibility, and the compiler ignores it.
Line 2: This is a directive to the compiler to allow defining classes.
Lines 4–7: We define
myClassusing the class keyword. Include a member variablevwithin this class.Lines 8–9: We declare two variables having as type the class already defined.
Lines 12–13: We create two instances of the class
myClassand store them in the variables previously declared.Line 14: We initialize the member variable
vof the first class instance to 5.Line 15: We initialize the member variable
vof the second class instance to 10.Line 16: We print out the values of the variable
vfor each instance. The values are local to each instance of the class.
Static fields
In the following example, we will learn about the static fields:
program hello;{$mode objfpc}typemyClass = classv : integer; static;end;varcl1,cl2 : myClass;beginwriteln('Start...');cl1:=myClass.create;cl2:=myClass.create;cl1.v:=5;writeln('cl1.v=',cl1.v,' cl2.v=',cl2.v);cl2.v:=10;writeln('cl1.v=',cl1.v,' cl2.v=',cl2.v);writeln('End...');end.
Code explanation
Lines 4–7: We define a class called
myClassusing the class keyword. We include a static member variablevwithin this class using the static modifier.Lines 15 and 17: We display the values of the variable
vfor both class instances. You will notice that all class instances will have a copy of the value of the variablev.
Free Resources