Question

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

Was it helpful?

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?

OTHER TIPS

All objects in java are references. final keyword means that the reference is final, but the object itself can be mutable. Look at Java's final vs. C++'s const .

Static keyword means that there is just single instance shared for all objects.

static in Java in general means static context, something corresponding to classes. In this case static field can be seen a field of a class. Static fields can also be seen as global variables.

final is very similar to const in C++, meaning that the reference or value can not be re-assigned.

When used together they mean a constant reference or values having global visibility.

You might also want to read JLS §8.3.1 Field Modifiers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top