1
.
public
class
HasStatic{
2
.
private
static
int
x=
100
;
3
.
public
static
void
main(String args[]){
4
. HasStatic hs1=
new
HasStatic();
5
. hs1.x++;
6
. HasStatic hs2=
new
HasStatic();
7
. hs2.x++;
8
. hs1=
new
HasStatic();
9
. hs1.x++;
10
. HasStatic.x--;
11
. System.out.println(
"x="
+x);
12
. }
13
. }
首先要了解static的意思。
static表示“全局”或者“静态”的意思,用来修饰成员变量和成员方法,也可以形成静态static代码块
static变量在第一次使用的时候初始化,但只会有一份成员对象。
所以这里不仅可以调用,而且每一次调用都确实修改了x的值,也就是变化情况是这样的:
x=101
x=102
x=103
x=102
x=102
x=103
x=102
本文通过一个具体的Java示例,详细解析了static关键字的作用及其在成员变量中的应用特点。特别是static变量仅有一份副本且在首次使用时初始化的特性。
311

被折叠的 条评论
为什么被折叠?



