简体   繁体   中英

Java enums, static class variables - why can't I do this?

I am getting a "cannot be resolved" error when I try to do this:

class Tag{
   public static final int blah = 1231; 
}

enum Things{
    COOL (Tag.blah, "blah"); //error here
}

the compiler complains that it cannot find the Tag class on the line above.

Visibility is probably the error here. Your class Tag has default visibility, so I guess your enum is not in the same package. Use public class Tag

EDIT:

this compiles from inside a common outer class:

class Tag {
    public static final int blah = 1231;
}

enum Things {
    COOL(Tag.blah, "blah"); // error here

    private Things(final int i, final String s) {
    }
}

The following complete EnumTest.java file compile. I'm not sure what your problem is; there isn't enough information.

public class EnumTest {
    class Boo {
        static final int x = 42;
    }
    enum Things {
        X(Boo.x);
        Things(int x) { }
    }
}

Have you defined the constructor of the COOL enum? You are passing it parameters, but the default constructor does not accept any.

Well turns out the error was just stupidity on my part.

I was referring to a member variable, ( blah in above example) that did not exist! So it wasn't resolving Tag.blah !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM