Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java constants and static modifiers

In java, constants as known as keyword (final) with a value that will never change. I have seen some people create constants without declaring a static modifier. My question is, should constants be declared as a static? If so or if not, why?

like image 718
TheDetailer Avatar asked Mar 14 '23 19:03

TheDetailer


1 Answers

If you assign a value to the final variable when declaring it, there's no point in it not being static, since each instance would have its own variable having the same value, which is wasteful.

However, if you need an instance variable whose value can only be set once (but different instances may have different values), that variable would have to be final but not static.

For example :

class Person 
{
    final int id;
    public Person(int id) {
        this.id = id;
    }
}
like image 105
Eran Avatar answered Mar 27 '23 18:03

Eran