2

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?

Makoto
  • 104,088
  • 27
  • 192
  • 230
  • 2
    You might want to check to make sure that that's the *only* constructor. If you have multiple constructors, then every one of them will need to initialize `storage`. Better yet, just write `private final Set storage = new HashSet();` to begin with, and you won't need to put it in a constructor. :-) – ruakh Mar 07 '12 at 23:04
  • I definitely only have one constructor. Are there any technical differences (on the bytecode / execution level) of initialization at the field rather than in the constructor? –  Mar 07 '12 at 23:05
  • I just posted an answer -- and I see that you edited your question to say the same thing. Regarding the technical differences between initializing in one place versus the other: Not really. From what I understand, the difference will be transmitted from the source-code to the bytecode (since one version goes in the `init` method instead of in the constructor), but that shouldn't have any *real* effect. – ruakh Mar 07 '12 at 23:12

3 Answers3

5

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • +1 I noticed that too, but I would have thought he'd see a different error in that case. – Aaron Mar 07 '12 at 23:11
2

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
    }
}
Makoto
  • 104,088
  • 27
  • 192
  • 230
-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.