static method in x++

 

Static methods, which are also known as class methods, belong to a class and are created by using the keyword static. You don't have to instantiate an object before you use static methods. Static methods are often used to work with data that is stored in tables. Member variables can't be used in a static method.

Static methods are generally intended for cases where the following criteria are met:

  • The method has no reason to access the member variables that are declared in the classDeclaration block of the class.

  • The method has no reason to call any instance (non-static) methods of the class.

If we will create a static method then we don't need to create any object of the class in which the static method exists.

Code: Class Declaration


// Fruit Class declaration
public class Fruit
{
  // no need to declare anything
}


Code: Staic method inside a class Fruit



public static void methodStatic()
{
    str name1 = 'hello';
    info("This is static method "); 
    info(strFmt("%1", name1));
    
}


Code: Access a static method from main method


public static void main(Args _args)
{
        Fruit::methodStatic();
 }

We can't access a class member or class attribute from a static method.


Comments