简体   繁体   中英

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?

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";

When you set the variable as final, you are telling everybody (the compiler, the runtime) that it cannot be changed. This can help a lot with optimizations like inlining all of the occurrences of the variable with its value.

Setting the reference to final ensures you can't change the reference. Note however that if the object referred to is mutable then you could still change that (not in this instance, since Strings are immutable ).

I normally make fields final and initialise them in the constructor. By favouring immutability my classes are easier to debug and are more likely to be safe in threaded environments. It's easier to remove the immutability constraint than add it.

I also do this for method arguments. Rarely (ever) do I want to change a method argument, and making them final will catch inadvertent assignments.

I try not to use static except for final constants. Unless it's something like a logger, I don't really want one instance per class, and (of course) this doesn't work in the case of multiple classloaders. It's also getting close to the singleton anti-pattern, and this impacts on easy testing and (potentially) threading.

When you have a constant string which can not be changed, you should make it a static final string.

Static means that less memory is needed for instance of the class, because the instances don't need individual copies.

Final allows some optimizations and thus makes your program faster.

There are few things good to know:

  • final variables can be checked by compiler that they are not accidentally changed.
  • references to non-static variables are contained in instance so there is small needless memory consumption in addition
  • static variables are shared across all instances of the same class, so you can be sure that all instances work with the same value
  • final static variables, especially the Strings are linked in compilation time so they need not to be dereferenced at runtime from the field. Due to that it cannot be changed even by the reflection, because such field is not used at runtime.

The fact that you make the variable static means that a single instance of that variable will be shared among all the instances of ClassOne , as the variable is bound to the class itself, not to its instances. Apart from any JVM optimisations, you'll have a single instance of reply for every instance of ClassTwo .

First one is Constant you need to know value of it at compile time.

private static final String reply = "Success";

second is just simple member variable. So any case first one is preferred since second one will create value for each object.

Assuming that you intended **private final String reply** in second case

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable.

In second case you can also declare and initialize it in constructor

 private final String reply;

You can read more about it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM