Tuesday 3 November 2015

Blank final variable

Blank final variable

Blank final variable in Java is a final variable which is not initialized while declaration, instead they are initialized on constructor.

There will compile-time error occurs if blank final variable is not initialized during construction because static and final variable are treated as compile time constant and there value is replaced during compile time only.

If you have more than one constructor or overloaded constructor in your class then blank final variable must be initialized in all of them, failing to do so is a compile-time error.

Alternatively you can use constructor chaining to call one constructor from other using this keyword, in order to delegate initialization of blank final variable.


/**
 * Blank final variable must be initialized in constructor.
 * Otherwise there will compile time error.
 */
public class Solution {
      //must be initialized in constructor
      private final int blankFinalVariable;

      public Solution() {
          this(6); // this is Ok : constructor chaining
          //this.blankFinalVariable = 3;
      }

      public Solution(int number) {
          this.blankFinalVariable = number;
      }

      public static void main(String args[]) {
          Solution sol = new Solution();
          System.err.println("Blank Final Variable :"+sol.blankFinalVariable);
      }
}
Output: Blank Final Variable: 6

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...