Skip to content

Instantly share code, notes, and snippets.

@Kaushal28
Created July 15, 2019 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kaushal28/e9c043d3a2d4d1969d2234018f1437d2 to your computer and use it in GitHub Desktop.
Save Kaushal28/e9c043d3a2d4d1969d2234018f1437d2 to your computer and use it in GitHub Desktop.
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