static变量的特点 - 只会有一份成员对象

时间:2023-03-08 21:43:19
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