user1255882
user1255882

Reputation:

Variable might not have been initialized

Here I am, thinking I know Java, and I get the error Variable 'storage' might not have been initialized. Here is my code:

public class RobbleSet {
    private final Set<Robble> storage; // Error occurs here

    public RobbleSet() {
        storage = new HashSet<Robble>();
    }

    public addRobble(Robble r) {
        storage.add(r); // Error occurs here too
    }
}

storage is initialized in the constructor. What gives?

Upvotes: 2

Views: 4389

Answers (3)

Suren Duhan
Suren Duhan

Reputation: 1

storage is declared as final and hence the error. For a final variable the values must be assigned in the constructor. The error in addRobble is also due to same, you cannot modify the value of a final variable in any method other than constructor.

Upvotes: -1

Makoto
Makoto

Reputation: 106508

addRobble doesn't have a return type so the static analyzer is picking it up as a constructor even though it isn't called RobbleSet. The proper code is as follows:

public class RobbleSet {
    private final Set<Robble> storage; // Error occurs here

    public RobbleSet() {
        storage = new HashSet<Robble>();
    }

    public void addRobble(Robble r) {
        storage.add(r); // Error occurs here too
    }
}

Upvotes: 2

ruakh
ruakh

Reputation: 183602

One problem is that you're not declaring a return type for addRobble; you need to change this:

    public addRobble(Robble r) {

to this:

    public void addRobble(Robble r) {

I suspect that this is the problem — that your compiler thinks that addRobble is a misnamed constructor, so is complaining that it fails to initialize storage — but even if it turns out that it's not the problem, it's definitely a problem.

Upvotes: 5

Related Questions