static关键字(pass)

静态变量和静态方法

  1. 修饰变量,变量叫静态变量,表示变量是类变量,不是实例变量,所有实例共享这一个变量。
  2. 修饰方法,方法叫静态方法,表示方法是类方法,不是实例方法,可以用类名.方法名直接调用,也可以实例化一个对象来调用。

  静态方法和静态变量都是类的静态资源,是类实例之间共享的。静态资源是类初始化的时候加载的,而非静态资源是实例初始化也就是new一个对象的时候加载的。所以:

  1. 静态方法不能引用非静态资源,因为静态方法调用时非静态资源有可能还没加载。
  2. 静态方法可以引用其它静态资源。
  3. 非静态方法可以引用静态资源,因为非静态资源调用时静态资源已经加载好了。

静态块

  静态块和静态变量/静态方法一样,也是在类初始化的时候执行,且只执行一次。静态块有三个需要注意的地方:

  1. 静态资源的加载顺序是严格按照静态资源的定义顺序来加载的。
  2. 静态代码块对定义在它之后的变量,只能赋值,不能访问。
  3. 在有继承关系的父子类中,静态代码块执行顺序是父类静态代码块先,子类静态代码块后,且只执行一次。

示例1:

package com.basic;

public class StaticBlockTest {

    public static int a = test();
    static {
        System.out.println("second");
    }
    
    static {
        System.out.println("first");
    }
    
    static int test() {
        System.out.println("third");
        return 1;
    }
    
    public static void main(String[] args) {
        StaticBlockTest test = new StaticBlockTest();
    }
}

结果:

third
second
first

示例2:

package com.basic;

public class StaticBlockTest {

    static int a = test();
    static {
        System.out.println("second");
    }
    
    static {
        System.out.println(b);
    }
    
    static int test() {
        System.out.println("third");
        return 1;
    }
    
    static int b = 4;
    
    public static void main(String[] args) {
        StaticBlockTest test = new StaticBlockTest();
    }
}

编译器报错:“Cannot reference a field before it is defined“

示例3:

package com.basic;

public class StaticBlockTest extends Father{

    static int a = test();
    static {
        System.out.println("second");
    }
    
    static {
//        System.out.println(b);
        System.out.println("first");
    }
    
    static int test() {
        System.out.println("third");
        return 1;
    }
    
    static int b = 4;
    
    public void print() {
        System.out.println("Child");
    }
    
    public static void main(String[] args) {
        StaticBlockTest test = new StaticBlockTest();
        test.print();
    }
}

class Father {
    static {
        System.out.println("Father");
    }
    
    public void print() {
        System.out.println("Father");
    }
}

结果:

Father
third
second
first
Child

静态内部类

import static

可以指定倒入某个类中的指定静态资源,并且不需要使用类名.资源名,可以直接使用资源名。

package com.basic;

import static com.imooc.demo2.StringBuilderDemo.IMPORT_STATIC;
public class ImportStaticTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.println(IMPORT_STATIC);
    }

}

结果:

import static key word
原文地址:https://www.cnblogs.com/IvySue/p/7488038.html