6

I want to define an outer class with two inner classes, the inner classes containing specific constants related to each of them. For example:

public class Stuff{

    public class Letters{
        public static final String A = 'a';
        public static final String B = 'b';
    }
    public class Numbers{
        public static final String One = '1';
        public static final String Two = '2';
    }
}

of course, when I try this, I get the error: Only top-level class variables can be declared static

any way to get around this? why does Salesforce not allow this? (does Java allow this?)

6

No, you cannot make them static. You can use inner-class constants by simply dropping the static modifier, however.

public class Stuff
{
    public class Letters
    {
        public final String A = 'a';
        public final String B = 'b';
    }
    public class Numbers
    {
        public final String One = '1';
        public final String Two = '2';
    }
}

You can also reference top-level constants from inner-classes.

public class OuterClass
{
    public static final String CONSTANT = 'ACME';
    public class InnerClass
    {
        public final String INNER_CONSTANT = CONSTANT;
    }
}

You can find some Java based explanation here.

See also:

Why are static variables allowed only in outer classes?

  • It should be noted that this solution will not work the other way around. So if you need to access the inner constant from the outer class or somewhere else in your code, you're stuck. In this case you cannot access the constant without an instance of the class (of course). I constantly hit this problem and this limitation drives me nuts. But maybe that's just me. – Semmel Oct 23 '18 at 17:00
  • I've never run into it being a problem. If it's a constant, you declare it at the top level. Not being able to do it the other way around is a limitation I have simply never run into. – Adrian Larson Oct 23 '18 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.