Why can final object be modified?

By | July 8, 2019

Question

I came across the following code in a code base I am working on:

public final class ConfigurationService {
    private static final ConfigurationService INSTANCE = new ConfigurationService();
    private List providers;

    private ConfigurationService() {
        providers = new ArrayList();
    }

    public static void addProvider(ConfigurationProvider provider) {
        INSTANCE.providers.add(provider);
    }

    ...

INSTANCE is declared as final. Why can objects be added to INSTANCE? Shouldn’t that invalidate the use of final. (It doesn’t).

I’m assuming the answer has to do something with pointers and memory but would like to know for sure.

Solution

final simply makes the object reference unchangeable. The object it points to is not immutable by doing this. INSTANCE can never refer to another object, but the object it refers to may change state.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *