Reputation: 11617
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.
Upvotes: 2
Views: 243
Reputation: 4732
Combining the answer of tbd and Xymostech + another info from me you can do the following.
1) On your code you declared the final variable like this final Class_A obj = null;
once you have assigned a final variable to a certain value you can no longer replace or reassign the value of it. For more information about that, please refer here and here
That being said you are not allowed to do this
if ( a == true){
final Class_A obj = new Class_A("a");
}else{
final Class_A obj = new Class_A("B");
}
2) if you are going to use some other value or a simple computation to detemine let's say a boolean you can do this
final Class_A obj = a ? new Class_A("a") : new Class_A("B");
Judging from your code, you can do both of that given choices I have given you.
But from your code you can do this.
void function_ab(){
final Class_A obj;
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.
}
Just remove the null assignment of final Class_A obj;
Upvotes: 2
Reputation: 9382
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.
Upvotes: 12
Reputation: 9850
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.
Upvotes: 2