Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class TestFinalVariable {
public final int foo;
// If variable is static and final, it must be initialized right away.
public static final int bar = 10;
//In constructor, initialization of final variable is allowed, as compiler knows that the constructor can only be called 1 time per object.
//Static variables can not be initialized even in constructor, as they are shared between multiple objects and that's why multiple object
//initialization can updathe the same copy of final variable, which is not allowed and thus static final variable must be initialized on declaration
TestFinalVariable(int foo) {
this.foo = foo;
}
public void updateFinal(int foo) {
//In method initialization of final variable is not allowed, as compiler knows that the method can be called multiple times.
// this.foo = foo;
}
}
public class FinalVariableExample {
public static void main(String[] args) {
TestFinalVariable testFinalVariable = new TestFinalVariable(28);
System.out.println(testFinalVariable.foo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment