When using Pascal, we can define static methods within a class.
Before we move on to how to create and use a static class method in Pascal, we must first understand what a static method is.
Static methods of a class are just like any other method. However, when implementing a static class method, the Self
identifier is not available. This means that static methods do not have access to any class variables or methods. Static methods cannot be virtual, nor can they be assigned to regular procedural variables.
Static methods are associated with the namespace of the class rather than the
Now that we have familiarized ourselves with the concept of static methods, it’s time to see them in action.
Let’s define our classes:
Type
ClassA = Class
Class procedure foo; virtual;
Class Procedure bar; static;
end;
ClassB = Class(ClassA)
Class procedure foo; override;
end;
We define two classes, ClassA
and ClassB
. ClassB
is derived from ClassA
.
ClassA
contains a virtual method (foo
) and a static method (bar
).
ClassB
is derived from ClassA
and overrides the foo
method.
Class procedure ClassA.foo;
begin
Writeln('ClassA.foo says: ', Self.ClassName);
end;
Class procedure ClassA.bar;
begin
foo;
Writeln('ClassA.bar says : ', ClassName);
end;
Class procedure ClassB.foo;
begin
Inherited;
Writeln('ClassB.foo says: ', Self.ClassName);
end;
The foo
method in ClassA
is a simple Writeln
statement that outputs the class name.
bar
is a static method and does not have a Self
identifier. Therefore, we use the ClassName
identifier to refer to the class name in the function defined in ClassA
.
The bar
method starts by calling the foo
function of its respective class followed by a simple Writeln
statement.
The overridden foo
method in ClassB
first calls the foo
method for its parent class (classA
), followed by a simple Writeln
statement.
Let’s writeup a main:
begin
Writeln('Through static method:');
ClassB.bar;
Writeln('Through class method:');
ClassB.foo;
end.
Through static method:
ClassA.foo says : ClassA
ClassA.bar says: ClassA
Through class method:
ClassA.foo says : ClassB
ClassB.foo says : ClassB
When the static method is called through ClassB
, the ClassName
identifier returns ClassA
. This is because the static method is only associated with ClassA
, as that was the class in which it was defined.
When we call the non-static method, the Self
identifier is correctly associated with ClassB
, and we see the right class names.