static对于变量意味着它是类作用域,而不是实例作用域.即它只有一个,由类的每个实例共享.当您static从类外部引用变量时,您需要使用类名限定它,而不是使用类的实例:
class Example {
static int staticVar = 0;
int instanceVar = 0;
}
Example ex = new Example();
ex.instanceVar = 1;
ex.staticVar = 2; // you may get an IDE/compiler warning for this
Example.staticVar = 3; // this is the best way to access your static variable
Run Code Online (Sandbox Code Playgroud)
Th static限定符也可以与方法(它表示相同)一起使用,对于内部类(这意味着内部类实例不绑定到外部类的任何实例).
volatile与并发编程有关; 它确保变量可以在多个线程之间共享(有一些限制).
所以两者没有太多共同之处,只是两者都可以限定变量.
| 归档时间: |
|
| 查看次数: |
4209 次 |
| 最近记录: |