11

I was searching on how to set the default value to a select List input on Visualforce and found the below trick:

public String selectedReminderTime {get; set;} {selectedReminderTime = '08:00 AM';}

What is this? Is this something similar to static blocks in Java http://www.jusfortechies.com/java/core-java/static-blocks.php

Could somebody please provide more details on this?

1
  • 1
    1+ i did not know that you set the value
    – Nick
    Jun 7, 2016 at 19:37

1 Answer 1

15

Apex Code is very similar to Java. You can have both static and instance initialization blocks anywhere such blocks are legal. These blocks run in source-code order, and must reference only elements that have already been defined at that point in the source code. Static blocks will run when a class is first entered by any means (e.g. referencing a static variable or function), and instance blocks will run before the constructor is called for that class.

Note that only back-references are allowed, so the following is illegal:

{
    x = 5;
}
Integer x;

While you've included them on the same line, which is perfectly logical, you may also have chosen to place it on a separate line, or even many lines down, or even create blocks with multiple statements that initialize many variables at once.

Note that, unlike constructors, these blocks are always called, which may be advantageous if you're trying to make sure a certain variable is always initialized no matter which of many potential constructors are called, which can reduce overall code use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.