Java实例化静态字段及静态块

首先,示例来自Bruce Eckel的《On Java》:

// housekeeping/ExplicitStatic.java
// (c)2021 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Explicit static initialization with "static" clause

class Cup {
  Cup(int marker) {
    System.out.println("Cup(" + marker + ")");
  }
  void f(int marker) {
    System.out.println("f(" + marker + ")");
  }
}

class Cups {
  static Cup cup1;
  static Cup cup2;
  
  Cups() {
    System.out.println("Cups()");
  }
  //add new static field
  static Cup cup3 = new Cup(3);
  static {
    cup1 = new Cup(1);
    cup2 = new Cup(2);
  }
}

public class ExplicitStatic {
  public static void main(String[] args) {
    System.out.println("Inside main()");
    Cups.cup1.f(99);                  // [1]
  }
   static Cups cups1 = new Cups();  // [2]
   static Cups cups2 = new Cups();  // [2]
}
/* Output:
// Inside main()
// Cup(1)
// Cup(2)
// f(99)
Cup(3)
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)
*/

 说明:按照实例化的语句顺序进行实例化,不是按照定义的顺序。另外,实例化顺序为:先静态->再动态->再构造函数,这样顺序进行。

再:

public class A {
    public static String c="C";
    static{
        System.out.println("A");
    }
}

public  class B extends A {
    static {
        System.out.println("B");
    }
    //public  static  String c="E";
}
public class  Test{
    public static void main(String[] args)
    {
        System.out.println(B.c);

    }
}

运行,结果为:

 

 打开class B public static String c="E";注释

再次编译,并运行:

 

posted @ 2022-11-08 08:48  Shapley  阅读(66)  评论(0编辑  收藏  举报