0% found this document useful (0 votes)
2 views2 pages

Static Keyword

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Static Keyword

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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.

Key Concepts of static:

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:

public class Car {


public static String brand = 'TATA'; // Static variable

public static void showBrand() { // Static method


System.debug(brand);
}
}

// No need to create an instance of Car to call the static method


Car.showBrand(); // Outputs: TATA

Shared Across All Instances:

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:

public class Car {


public static String brand = 'TATA';
}

Car.brand = 'Tesla'; // Changing the static variable


System.debug(Car.brand); // Outputs: Tesla for all instances of the class
Static Methods:

 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:

public class MathUtils {


public static Integer add(Integer a, Integer b) {
return a + b;
}
}

// Usage without needing an instance


Integer result = MathUtils.add(5, 10); // Outputs: 15

When to Use static:

Use static when the data or behavior is not tied to any specific instance of a class. For
example:

1. Utility methods (e.g., MathUtils.add)


2. Constants or configurations that apply to the class as a whole
3. Caching values that are shared across instances

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.

You might also like