Search code examples
javastaticconstantsfinal

On the static final keywords in Java


According to the tutorial:

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.

I would agree with this only if the types involved were primitive. With reference types, e.g. an instance of a class Point2D where its position attributes were not final (i.e., we could change its position), the attributes of this kind of variables such as public static final Point2D A = new Point2D(x,y); could still be changed. Is this true?


Solution

  • Yes, it can be changed. Only the references cannot be changed, but its internal fields can be. The following code shows it:

    public class Final {
        static final Point p = new Point();
        public static void main(String[] args) {
            p = new Point(); // Fails
            p.b = 10; // OK
            p.a = 20; // Fails
        }
    }
    
    class Point {
        static final int a = 10;
        static int b = 20;
    }
    

    Groovy (an alternative JVM language) has an annotation called @Immutable, which blocks changing to a internal state of an object after it is constructed.