企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### [非静态实例初始化](https://lingcoder.gitee.io/onjava8/#/book/06-Housekeeping?id=%e9%9d%9e%e9%9d%99%e6%80%81%e5%ae%9e%e4%be%8b%e5%88%9d%e5%a7%8b%e5%8c%96) Java 提供了被称为*实例初始化*的类似语法,用来初始化每个对象的非静态变量,例如: ~~~ // housekeeping/Mugs.java // Instance initialization class Mug { Mug(int marker) { System.out.println("Mug(" + marker + ")"); } } public class Mugs { Mug mug1; Mug mug2; { // [1] mug1 = new Mug(1); mug2 = new Mug(2); System.out.println("mug1 & mug2 initialized"); } Mugs() { System.out.println("Mugs()"); } Mugs(int i) { System.out.println("Mugs(int)"); } public static void main(String[] args) { System.out.println("Inside main()"); new Mugs(); System.out.println("new Mugs() completed"); new Mugs(1); System.out.println("new Mugs(1) completed"); } } ~~~ 输出: ~~~ Inside main Mug(1) Mug(2) mug1 & mug2 initialized Mugs() new Mugs() completed Mug(1) Mug(2) mug1 & mug2 initialized Mugs(int) new Mugs(1) completed ~~~ 看起来它很像静态代码块,只不过少了**static**关键字。这种语法对于支持"匿名内部类"(参见"内部类"一章)的初始化是必须的,但是你也可以使用它保证某些操作一定会发生,而不管哪个构造器被调用。从输出看出,实例初始化子句是在两个构造器之前执行的。