Static methods and attributes
A real, mathematical function doesn't use variables declared outside
its body. Methods that are pure functions, and thus that don't use attributes
of the class (but if static also) are considered as static, and may
be called directly associated to the class name instead the name of
an instance. As said above, this is good practice to put related functions
inside classes, just to make the program clearer and to build reusable
components.
Example of static call for the Path class:
node, extension = Path.splitExt(pathname)
An attribute declared as static may also be associated with the name
of the class, or the name of an instance. A static attribute shares
its content with all instances, including inherited ones. A static method
can only use static attributes. It can't call other methods.
Examples: The name of the or the name of the instance may be used as well for static members. |
class
Car static usine = "Xxx" static void setName(text x) usine = x return /class Car myCar Car .setName("name") myCar.setName("name") Car.factory = "name" myCar.factory = "name" |
All these statements have the same result but only static members may be called along with the class' name. Sf you change a static attribute for an instance, this change applies to all other instances of the same class.
Exercises |
1) The "add" function is defined above: |