Search code examples
javastaticfinal

Java Code Static Final variable usage


I've got two classes below. Both have one variable 'reply' with a getter. There is no setter method for this variable. Only difference is in ClassOne, the variable is static final.

So whats the difference and which one is preferred?

public class ClassOne {

    private static final String reply = "Success";
    ..

    public String getReply() {
        return reply;
    }

    // no setter

}

and Class 2

public class ClassTwo {

    private String reply = "Success";
    ..

    public String getReply() {
        return reply;
    }

    // no setter
}

UPDATE 1:

What I want to know is that when there is no setter for a variable, should the variable be declared as static final for optimization? or does it not matter?


Solution

  • should the variable be declared as static final for optimization?

    • final certainly, not only for optimization but for clarity and because it can make your object immutable, which is always a good thing to have.

    • static completely changes the nature of the field and has nothing to do with the existence of setters: do you want only one instance of that field, or do you need one per instance of your class?

    • Non static example: a Person has a name, which is a constant (for a given person = per instance), so you can use a non static final field, which you only set once when creating a new Person:

            private final String name;
    
    • Static example: Whenever you don't have a name for a Person, you want to use a default value - that is a global constant which is shared among all persons that don't have a name and you can use a static final field:
            private static final String NO_NAME = "John Doe";