Java Explicit static Initialization

本文深入探讨Java中静态初始化的概念,通过实例演示了静态初始化块如何仅在第一次创建类的对象或访问类的静态成员时执行一次。文章展示了不同情况下静态初始化的执行顺序,帮助读者理解其在Java内存模型中的作用。
摘要由CSDN通过智能技术生成

Static initializations, is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).

// housekeeping/ExplicitStatic.java
// (c)2017 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;

  static {
    cup1 = new Cup(1);
    cup2 = new Cup(2);
  }

  Cups() {
    System.out.println("Cups()");
  }
}

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]
}
/* When [1] is uncommented, [2] are commented. Output:
Inside main()
Cup(1)
Cup(2)
f(99)

When both [1] and [2] are uncommented. Output:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()
f(99)

When [1] is commented, [2] are uncommented. Output:
Cup(1)
Cup(2)
Cups()
Cups()
Inside main()

When both [1] and [2] are commented. Output:
Inside main()
*/

then change the code order

// housekeeping/ExplicitStatic.java
// (c)2017 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 {
    // cup1 = new Cup(1);
    cup2 = new Cup(2);
  }

  static Cup cup1 = new Cup(1);
  static Cup cup2;

  Cups() {
    System.out.println("Cups()");
  }
}

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]
}
/* My Output:
Inside main()
Cup(2)
Cup(1)
f(99)
*/

for better understand, please read below content.

see instance initialization.

see initialization with inheritance.

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/housekeeping/ExplicitStatic.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值