Created
July 15, 2019 16:09
-
-
Save Kaushal28/e9c043d3a2d4d1969d2234018f1437d2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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