setting default value for properties in controller

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?

Answer

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.

Attribution
Source : Link , Question Author : javanoob , Answer Author : sfdcfox

Leave a Comment