Search code examples
javajakarta-eefinal

Java final variable in function


void function_ab(){

if ( a == true){
    final Class_A obj = new Class_A("a"); //This is an example scenario, so I couldn't create a setter to pass in "a" instead of passing it into Contructor.
}else{
    final Class_A obj = new Class_A("B");
}

// the code below will access obj object in Inner class.

}

I need to access obj after the declaration, but since they are declared in 'if' block, I will not be able to access it after that. I can't do such thing like this also:

void function_ab(){

final Class_A obj = null;
if ( a == true){
    obj = new Class_A("a"); //final variable cannot be changed.
}else{
     obj = new Class_A("B");
}

// the code below will access obj object in Inner class.

}

The code above is not valid. So is the only way to get it works is to declare the obj variable as class variable? I try to avoid declaring like that because it only be used in that function only.

Please tell me if there is better way in solving this.


Solution

  • Instead of using:

    final Class_A obj = null;
    

    You should be able to use

    final Class_A obj;
    

    This will allow you to initialize obj within an if statement- for more information, check out this description of blank finals from Wikipedia, a source that we may all trust with our lives.