Search code examples
javastaticinner-classesfinal

Why static final variables are accepted in inner classees?


I know that it's possible to do the following:

public class Indeed{
    private class inner {
        static final int try1 = 10;
    }
}

Why? what's the point of allowing such a declaration? Moreover it's still possible do the same thing in a local class:

public void doThing() {
    class LocalClass {
         static final int try1 = 10;
    }
}

What's the use of a static final in those bits of code? I am pretty sure I'll never use them, however I need to understand why they are used as I have an OCPJP7 exam to do.

Thanks in advance.


Solution

  • The purpose of a static variable is to be shared by all instances of the class. In both examples, you can have several instances of your private class / local class, so as specified they will share static variables among instances. What would be pointless is if you could only instantiate your class once.

    JLS 8.1.3. : Inner Classes and Enclosing Instances

    Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.

    The way I see it in the specs, is not having to answer the following dilemma:

    • static variables of an inner class are shared amongst all instances of the same outer class instance (but they can have different values from an outer class instance to another)
    • static variables of an inner class are shared amongst all existing instances in the VM, whatever their outer class instances.

    Fortunately, when you declare it final, you know it will be the same for every instance, so you don't have to worry about this problem. That's why it is allowed.