Search code examples
javadesign-patternsconstructorinitialization

Java: design problem with final-value and empty constructor


$ javac InitInt.java 
InitInt.java:7: variable right might not have been initialized
 InitInt(){}
           ^
1 error
$ cat InitInt.java 
import java.util.*;
import java.io.*;

public class InitInt {
 private final int right;

    // Design Problem?
    // I feel the initialization problem is just due to bad style.

 InitInt(){}
    InitInt{
           // Still the error, "may not be initialized"
           // How to initialise it?

            if(snippetBuilder.length()>(charwisePos+25)){
                    right=charwisePos+25;
            }else{
                    right=snippetBuilder.length()-1;
            }
    }

 public static void main(String[] args) {
  InitInt test = new InitInt(); 
  System.out.println(test.getRight());
 }
 public int getRight(){return right;}
}

Partial Solutions and Suggestions

  1. use "this" to access methods in the class, instead of creating empty constructor
  2. change final to non-final
  3. with final field value: initialize all final values in every constructor
  4. remove the empty constructor, keep your code simple and clean

Solution

  • Yeah, the problem is that one of your constructors doesn't initialize the final field. In Java final non-static fields have to be initialized at the declaration time, in an initialization block, OR in EVERY constructor! The default constructor in your example doesn't do that. Remember as well that implementing an empty default constructor makes sense only if you want to use inheritance features. If you don't provide a default constructor, but you will some other one Java won't make a hidden default constructor for you, because the default one is not required. So don't implement things like MyClass() {} with no special purpose - keep your code clean and save!