一文搞懂 static 静态变量,静态方法,静态块

static 静态变量

定义格式 静态变量由static关键字修饰的变量

public static int staticVariable = 1 ; //定义静态变量
 public int normolVariable = 2 ; //普通变量

调用方法 我们现在example27类中写一个普通方法

public class example27 {
          
   
 public void test(int a) {
          
   
 System.out.println(a);
 }
}

然后在example28中写一个静态变量并测试,我们由example27中的普通方法来使用example28中的静态变量

public class example28 {
          
   
 public static int staticVariable = 1 ; //定义静态变量
 public int normalVariable = 2 ; //普通变量
 
 public static void main(String args[]) {
          
   
 example27 example2 = new example27() ;
 example2.test(staticVariable);    //由静态变量所属类之外的类使用这个静态变量
 }
}

使用场景 静态变量的强大之处可以在于由静态变量所属类之外的类使用这个静态变量。如 我们定义的通用异常错误类,很多异常状态需要被大量的访问,所以可以将状态信息设置成静态变量让其他的类更方便的去使用。 单例模式也是static非常重要的应用。地址:

内存分配访问 在类初始化的时候,静态变量不同于其他的变量,静态变量会在类中单独的分一块特殊的公共区域,这块区域中有一个地址就是我们的静态地址,静态变量就是指向这块地址的变量。

静态变量在类进行初始化时候便分配了内存。 普通变量只有类进行实例化的时候进行内存分配。

static 静态方法

定义格式 用static修饰的方法叫静态方法

public static void staticTest() {
          
   
      System.out.println("static text");
 }

调用方法

public class example27 {
          
   
	public static void staticTest(int variable) {
          
   
 		System.out.println("static text");
 	}
}
public class example28 {
          
   
 public static int staticVariable ; //定义静态变量
 public int normalVariable = 2 ; //普通变量
 
 public static void main(String args[]) {
          
   
 		Example27.staticTest(staticVariable) ; //不需要实例化即可调用静态方法
 }
}

注意一点:如果在static方法内访问一个非静态的成员变量这是错误的,因为在类内初始化的时候还没有给普通成员变量分配内存

public int b ;
public static void staticTest(int variable) {
          
   
	 System.out.println("static text");
	 b++ ;   //错误
}

如果想使用普通变量,需要通过方法接口传入。

内存分配 静态方法和静态变量都是在类加载后便有了生命。 对象则是在实例化之后才有了生命

static 静态块

定义格式

static{
          
   代码块}
static {
          
   
 int test=1 ;
 System.out.println(test);
 example27.staticTest(staticVariable) ; 
}

执行顺序 1.static代码块在类的初始化时候最先执行,先于静态变量和方法

2.存在多个static代码块时候,按他们在类中出现的顺序执行

作用域 1.static代码块内定义的变量作用域代码块内部

2.代码块也只能调用静态变量和静态方法

总结 1.jvm只为每个类的static代码块分配一次内存

2.static{}块最先被执行

3.访问静态变量要先访问代码块实例化的类

经验分享 程序员 微信小程序 职场和发展