Search code examples
javaencapsulationfinalstatic-members

understanding a final static use on a map field of a class


I am c++ developer and trying to familiarize with Core Java concepts. i found this confusing as to my final static is something it cannot be changed after the object is constructed. (correct me if i am wrong)

I came across the below implementation which i found confusing as it seems to allow value getting added into Map even when it is final static

public class MockUserServiceImpl implements UserService {

    private static final Map<String, User> userMap = new HashMap<String, User>();

    public static void addUserToCache(int userId, String userName) {
        if (!userMap.containsKey(userName)) {
            userMap.put(userName, new User(userId, userName));
        }
    } 
}

Can someone try to explain me what exactly the static final here is meant to


Solution

  • Don't think of Map as a data structure. Think of it as any other class that has methods, for example put(..). Are you saying that if you had

    public class Foo {
        public void bar() {}
    }
    

    you shouldn't be able to call bar() on

    final Foo foo = new Foo();
    

    simply because it's final? What use would it have then?

    The final keyword only prevents a variable from being reassigned, not what methods can be called or what fields can be accessed. It has a different meaning when used on on methods and classes.

    As for static, read:

    What does the 'static' keyword do in a class?