Apex Class
public class ApexClass {
public static final Integer x=19;
static {
x = 12;
}
public static void ApexMethod(){
System.debug(x);
}
}
Apex Code
ApexClass.ApexMethod();
Execution Log
DEBUG | Final variable has already been initialized
Considerations
- Final variables can only be assigned a value once, either when you declare a variable or inside a constructor. You must assign a value to it in one of these two places.
- Static final variables can be changed in static initialization code or where defined.
- Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
- To define a constant, mark a variable as both static and final.
- Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they are not shared across requests.
- Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This means they cannot be overridden. Use the virtual keyword if you need to override a method or class.