when we declare a variable as final we need to initialize it in the
same line with a constant value
A counter-example would be:
public class QuickTest {
private final int x;
{
x = 5;
}
private final static int y;
static {
y = 5;
}
public QuickTest() {
}
}
I do this sometimes when I want to set a final
field with multiple lines of code (ie not just a single method call). These {}
enclosures also allows me the opportunity to wrap everything in a proper try-catch
if I want to. Remember, in your example - if #newMethod1()
threw an error then your class would fail to instantiate. Just an example to illustrate:
public class QuickTest {
private final int x;
{
try {
int someCalculation = 5 + 3;
someCalculation += 10;
// set it
x = someCalculation;
} catch (Exception e) {
// handle exception if we can
;
// unrecoverable error, so let the calling code fail :(
// LogManager.error(this, e);
throw new RuntimeException(e);
}
}
public QuickTest() {
}
}
A link to the Java spec on final
HERE