Java: OOP: static Keyword

21st January 2021 at 10:43pm
Java: Language: OOP

Static Variable, Block, Method

public class ClassDemo {
    // Static variable. Use `ClassDemo.num` when accessed by outside
    static int num;
    int size;

    // Static blocks. Would be executed in sequence before constructor was called
    // You can't assign a value to non-static variable in static blocks.
    static {
        num = 17;
        System.out.println("Executing static block 1");
    }

    static {
        System.out.println("Executing static block 2");
    }

    // Static variable can be changed by instance method, But it's not practical.
    void changeNum1() {
        num = 10;
        size = 20;
    }

    // Static variable can be changed by static methods.
    // Use `ClassDemo.changeNum2()` when accessed by outside
    // You can't assign a value to non-static variable in static methods.
    static void changeNum2() {
        num = 11;
    }
}

Static context 包含:

  • Static block
  • Static method

在 static context 中,你不能:

  • 访问非静态成员变量
  • 调用非静态方法
  • 使用 this, super 关键字。this, super 指向的是 instance。假如 Child 类继承 Parent 类,如果你要:
    • 调用子类或者父类的静态函数,使用 Child.staticFunc(), Parent.staticFunc()
    • 访问子类或者父类的静态成员函数,类似上一条

Static Class

参考 Java: OOP: Nested Class

参考: