There are two kinds of executable blocks in Apex. There are static blocks and instance blocks. Static blocks can be anonymous blocks and static methods. Instance blocks come in two basic flavors: constructors and methods. Outside of these blocks, the only executable statements that are allowed are for initializers.
Static blocks look like this:
public class MyClass {
static {
System.debug('this will be called first.');
}
public static void method() {
System.debug('This will only be logged when the method is called.');
}
}
The anonymous blocks are called in source order from top to bottom. Static methods are only called when specifically called elsewhere (e.g. MyClass.method()
).
Instance blocks look like this:
public class MyClass {
public MyClass() { // This is a constructor
System.debug('A new instance is being created.');
}
public void method() {
System.debug('This method was called on an instance.');
}
}
Constructors are only called when the new
keyword is used, and cannot be called like a normal method.
MyClass varName = new MyClass();
Instance methods are only accessible on an instance, which is an object that's been constructed:
MyClass varName = new MyClass();
varName.method();
It is an error to try to call an instance method as a static method, and vice versa.
Finally, there are initializers. These can be for static and instance properties.
public class MyClass {
public static Integer staticNumber = Crypto.getRandomInteger();
public Integer localNumber = Crypto.getRandomInteger();
}
Here, you can see that a method is called to initialize variables. Static variables are initialized top-down, as well as instance variables. Methods that do not return a value (void
return type) cannot be used as initializers, as there is no way to define a void
variable, and void
is not an Object
.
To sum up so far, you must generally have executable code inside some kind of executable block, of which four types exist. Therefore, if you didn't want to write a full "method", you could write:
public class MyClass {
static Integer value = 10;
static {
System.debug(value);
}
}
Note that you'll eventually run across Execute Anonymous scripts. These are special in that you can write executable code directly without a method.
System.debug('In executeAnonymous, this is allowed.');
class Myclass() {
void method() {
System.debug('Calling a method here.');
}
}
new Myclass().method();
If you're new to programming, consider reading the Apex Developer Guide from Getting Started With Apex through Debugging, Testing, and Deploying Apex, or take the Trailhead. There's a lot of great content out there if you go looking for it.