Static Keyword
Static Keyword
In Apex (and other object-oriented languages like Java), the static keyword is used
to indicate that a method, variable, or block belongs to the class itself rather than to
instances of the class.
Class-Level Association:
1. When you declare a method or variable as static, it belongs to the class itself,
not to any particular object or instance of the class.
2. This means you can call a static method or access a static variable without
creating an object of the class.
Example:
1. Static variables are shared across all instances of a class. If you change the value of a
static variable, that change is reflected across all instances of the class.
Example:
A static method can only access static variables or other static methods directly. It
cannot access instance variables (non-static) because instance variables are tied to
individual objects, not the class as a whole.
Static methods are often used when behavior or functionality is general and does
not depend on specific object state (i.e., it’s the same for all instances).
Example:
Use static when the data or behavior is not tied to any specific instance of a class. For
example:
Summary:
static members belong to the class, not to any instance.
static methods can only interact with other static members.
static members are shared across all instances of the class, and changes to them are
reflected globally.