Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 442
Sam YC Avatar asked Jan 31 '26 16:01

Sam YC


2 Answers

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.

like image 185
username tbd Avatar answered Feb 02 '26 07:02

username tbd


You could do

final Class_A obj = a ? new Class_A("a") : new Class_A("B");

However, I don't know if there's a way to do this with more complex conditions.

like image 45
Xymostech Avatar answered Feb 02 '26 08:02

Xymostech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!