简体   繁体   中英

Difference between a static and a final static variable in Java

Generally, final static members especially, variables (or static final of course, they can be used in either order without overlapping the meaning) are extensively used with interfaces in Java to define a protocol behavior for the implementing class which implies that the class that implements (inherits) an interface must incorporate all of the members of that interface.


I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?


A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?

The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.

public static void main(String args[])
{
    final int a=0;  //ok

    int b=1;  //ok

    static int c=2;  //wrong

    final static int x=0;  //wrong
}

You are making a huge mix of many different concepts. Even the question in the title does not correspond to the question in the body.

Anyways, these are the concepts you are mixing up:

  • variables
  • final variables
  • fields
  • final fields
  • static fields
  • final static fields

The keyword static makes sense only for fields, but in the code you show you are trying to use it inside a function, where you cannot declare fields (fields are members of classes; variables are declared in methods).

Let's try to rapidly describe them.

  1. variables are declared in methods, and used as some kind of mutable local storage ( int x; x = 5; x++ )

  2. final variables are also declared in methods, and are used as an immutable local storage ( final int y; y = 0; y++; // won't compile ). They are useful to catch bugs where someone would try to modify something that should not be modified. I personally make most of my local variables and methods parameters final . Also, they are necessary when you reference them from inner, anonymous classes. In some programming languages, the only kind of variable is an immutable variable (in other languages, the "default" kind of variable is the immutable variable) -- as an exercise, try to figure out how to write a loop that would run an specified number of times when you are not allowed to change anything after initialization! (try, for example, to solve fizzbuzz with only final variables!).

  3. fields define the mutable state of objects , and are declared in classes ( class x { int myField; } ).

  4. final fields define the immutable state of objects , are declared in classes and must be initialized before the constructor finishes ( class x { final int myField = 5; } ). They cannot be modified. They are very useful when doing multithreading, since they have special properties related to sharing objects among threads (you are guaranteed that every thread will see the correctly initialized value of an object's final fields, if the object is shared after the constructor has finished, and even if it is shared with data races). If you want another exercise, try to solve fizzbuzz again using only final fields, and no other fields, not any variables nor method parameters (obviously, you are allowed to declare parameters in constructors, but thats all!).

  5. static fields are shared among all instances of any class . You can think of them as some kind of global mutable storage ( class x { static int globalField = 5; } ). The most trivial (and usually useless) example would be to count instances of an object (ie, class x { static int count = 0; x() { count++; } } , here the constructor increments the count each time it is called, ie, each time you create an instance of x with new x() ). Beware that, unlike final fields, they are not inherently thread-safe; in other words, you will most certainly get a wrong count of instances of x with the code above if you are instantiating from different threads; to make it correct, you'd have to add some synchronization mechanism or use some specialized class for this purpose, but that is another question (actually, it might be the subject of a whole book).

  6. final static fields are global constants ( class MyConstants { public static final double PI = 3.1415926535897932384626433; } ).

There are many other subtle characteristics (like: compilers are free to replace references to a final static field to their values directly, which makes reflection useless on such fields; final fields might actually be modified with reflection, but this is very error prone; and so on), but I'd say you have a long way to go before digging in further.

Finally, there are also other keywords that might be used with fields, like transient , volatile and the access levels ( public , protected , private ). But that is another question (actually, in case you want to ask about them, many other questions, I'd say).

Static members are those which can be accessed without creating an object. This means that those are class members and nothing to do with any instances. and hence can not be defined in the method.

Final in other terms, is a constant (as in C). You can have final variable inside the method as well as at class level. If you put final as static it becomes "a class member which is constant" .

final keyword simply means "this cannot be changed".It can be used with both fields and variables in a method.When a variable is declared final an attempt to change the variable will result to a compile-time error.For example if i declare a variable as final int x = 12; trying to increment x that is (++x) will produce an error.In short with primitives final makes a value a constant. On the other hand static can only be applied with fields but not in methods.A field that is final static has only one piece of storage.final shows that it is a constant(cannot be changed), static shows it is only one.

In Java, a static variable is one that belongs to class rather than the object of a class, different instances of the same class will contain the same static variable value.

A final variable is one that once after initialized ,after the instantiation of a class (creation of an object) cannot be altered in the program. However this differ from objects if a different value is passed post creation of another object of the same class.

final static means that the variable belongs to the class as well as cannot be change once initialized. So it will be accessible to the same value throughout different instances of the same class.

I'm unable to differentiate between a final and a final static member. The final static member is the one which is a static member declared as final or something else? In which particular situations should they be used specifically?

Use a final static when you want it to be static . Use a final (non-static) when you don't want it to be static .

A static variable or a final static variable can never be declared inside a method neither inside a static method nor inside an instance method. Why?

Design decision. There's just no way to answer that without asking James Gosling.

The following segment of code accordingly, will not be compiled and an compile-time error will be issued by the compiler, if an attempt is made to compile it.

Because it violates the rule you just described.

只是在@Bruno Reis 的答案中添加一个次要信息,我试图完成答案,因为他谈到了在构造函数结束之前初始化最终字段的重要条件,最终静态字段也必须在静态块执行完成之前初始化.

你不能在静态块中声明静态字段,静态字段只能属于一个类,因此编译器错误。

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