Methods
Apex Static Methods
Static Methods
Apex static methods use static for shared logic.
What are Apex Static Methods?
In Apex, static methods are associated with a class rather than an instance of a class. This means you can call a static method without creating an object of the class. They are defined using the static
keyword and are typically used for utility or helper methods that perform operations not dependent on instance variables.
Defining Static Methods
To define a static method in Apex, use the static
keyword followed by the return type, method name, and any parameters. Here's the basic syntax:
In this example, the add
method is a static method that takes two integers as parameters and returns their sum. You can call this method without creating an instance of MathOperations
:
When to Use Static Methods
Static methods are best utilized when you need to create methods that are shared across all instances of a class or when the method doesn't rely on instance-specific data. Common scenarios include:
- Utility or helper methods that perform simple operations.
- Calculations or operations that don't require object state.
- Accessing or modifying static variables.
Limitations of Static Methods
While static methods are useful, they come with some limitations:
- They cannot access instance variables or methods directly. To access instance data, you need to pass it as a parameter.
- They cannot be overridden by subclass methods, meaning static methods do not follow polymorphism.
- They are not bound to any specific object instance.
Static Methods vs Instance Methods
Static methods and instance methods serve different purposes in Apex:
- Static Methods: Belong to the class and can be called without creating an instance. They are suitable for operations not dependent on instance-specific data.
- Instance Methods: Require an instance of the class to be called and can access the instance variables and methods.
Methods
- Methods
- Static Methods
- Instance Methods
- Virtual Methods
- Previous
- Methods
- Next
- Instance Methods