Rogue
Rogue

Reputation: 11483

How would this final variable be already assigned and not initialized?

I have a final variable, save, that is a serializble class for some information. What I've attempted to do is to set a final variable as that serializable class, however I get some conflicting warnings. I'm attempting to make it so that if the file isn't loadable / doesn't exist, it will simply create a new instance, otherwise it will use the old one.

My issue as it stands is commented in the code at the constructor opening, closing, and on reading the object from the ObjectInputStream

private final CannonSet save;


public CannonManager(ManCannon plugin) { // Warning that save is not initialized
    if (/* some conditional statement */) {
        //lot of code removed, unnecessary to problem
        //essentially, save was set conditionally here (loaded from file)
        this.save = new CannonSet();
    }
    if (this.save == null) {
        this.save = new CannonSet(); // Warning that save may have already been set
    }
}

Upvotes: 1

Views: 164

Answers (3)

Rogue
Rogue

Reputation: 11483

I found that using a temp variable throughout the constructor made this a lot simpler:

private final CannonSet save;

public CannonManager(ManCannon plugin) {
    CannonSet temp = null;
    /* code .... */
    if (temp == null) {
        this.save = new CannonSet();
    } else {
        this.save = temp;
    }
}

Upvotes: 1

MadConan
MadConan

Reputation: 3767

It looks like you just need to declare your temp object at full method scope, test if it's null at the bottom where you are checking this.save instead, and then do the assignment. Basically, just have one line ONLY where you assign the instance field. Abbreviated from your code:

public CannonManager(ManCannon plugin) {
    CannonSet temp = null;
    try{
       // stuff happens
       temp = (CannonSet) in.readObject();
    }catch( ... ){
       // exception handling
    }
    if(temp == null){
       this.save = new CannonSet();
    }else{
       this.save = temp;
     }
 }

Upvotes: 2

Andrey Chaschev
Andrey Chaschev

Reputation: 16496

You can't do this to a final variable:

if (this.save == null) {
    this.save = new CannonSet(); // Warning that save may have already been set
}

If save was initialized - and only in this case comparison to null is possible, then you can't reassign it.

Conditional logic is possible with final variables and in many cases it looks similar to:

final CannonSet save;

if(condition1){
    save = new CannotSet(1);
} else
if(condition2){
    save = new CannotSet(2);
} else {
    save = new CannotSet(3); 
}

Upvotes: 2

Related Questions