Rule Definition
If a Final Instance Variable is not dynamically initialized, its value will be the same for all Instances and need not be an Instance Variable. This final instance variable requires memory for each new instantiation while it could be declared as static and require memory only once for all instances of the class.
Remediation
Review the Field declaration to add the Static modifier.
Violation Code Sample
class Test { final int x; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } } Output: error: variable x not initialized in the default constructor
Fixed Code Sample
Initialization before constructor completion class Test { final int x = 10; public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } } Output: 10 --------------------------------------------------------- We can also initialize a final instance variable inside a non-static or instance block also. class Test { final int x; { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } } Output: 10 ------------------------- Inside default constructor we can also initialize a final instance variable. class Test { final int x; Test() { x = 10; } public static void main(String[] args) { Test t = new Test(); System.out.println(t.x); } } Output: 10 ---------------------------------------------- The above mentioned are the only possible places to perform initialization for final instance variable. If we try to perform initialization anywhere else then we will get compile time error. // Declare final instance variable within any static blocks class Test { final int x; public static void main(String[] args) { x = 10; Test t = new Test(); System.out.println(t.x); } } Output: error: non-static variable x cannot be referenced from a static context // Declare or initialize final instance variable within any methods class Test { final int x; public void m() { x = 10; } } Output: error: cannot assign a value to final variable x
Related Technologies
JEE
Technical Criterion
Programming Practices - Modularity and OO Encapsulation Conformity
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.