Search code examples
javaintfinal

Blank final variables


I'm trying to combine

  1. public access to variable
  2. non static variable
  3. not predifined value
  4. one time set value (final)
  5. int or Integer

Updated code is not working and the answer on 'how to do it' must be pretty simple, but I need help:

public class foo
{
    public final int smth; //Variable might not have been initialized
    public final Integer smthElse; //Variable might not have been initialized

    public foo(JSONObject myObj)
    {
        if(myObj != null) {
            try {
                int extraParam = Integer.parseInt("ABCD"); //This is just an example for Exception to be called
                smth = extraParam;
                smthElse = extraParam;
            } catch (Exception e) {}
        } else {
            smth = 1;
            smthElse = 2;
        }
    }
}

P.S. I don't want to use (private int + public getter + private setter)


Solution

  • When you perform an assignment within a try block, the compiler treats it as “may or may not have happened” after the try … catch … construct, which makes it ineligible for final variables you want to use after that construct.

    The solution is to use temporary non-final variables which you can assign multiple times and perform a definite assignment of the final variables at the end of the operation.

    E.g.

    public class Foo
    {
        public final int smth;
        public final Integer smthElse;
    
        public Foo(JSONObject myObj) {
            int smthValue = 1;
            Integer smthElseValue = 2;
    
            if(myObj != null) try {
                int extraParam = Integer.parseInt("ABCD"); //This is just an example
                smthValue = extraParam;
                smthElseValue = extraParam;
            } catch (Exception e) {}
    
            smth = smthValue;
            smthElse = smthElseValue;
        }
    }