1

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

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
linux developer
  • 821
  • 1
  • 13
  • 34

3 Answers3

5

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?

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

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.

Community
  • 1
  • 1
Viktor K.
  • 2,670
  • 2
  • 19
  • 30
0

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.

Andrey Chaschev
  • 16,160
  • 5
  • 51
  • 68
  • yes i found the explanation trying to give an analogy with const pointer in c++ where we cannot change the pointer what it points to. – linux developer Dec 24 '13 at 21:11