首页 > 代码库 > 非静态实例初始化

非静态实例初始化

  Java中也有被称为实例初始化的类似语法,用来初始化每一个对象的非静态变量。例如:

  //:  initialization/Mugs.java

  //  Java "Instance Initialization."

  class Mug {

    Mug(int marker) {

      System.out.println("Mug(" + marker + ")");

    }

    void f(int marker) {

      System.out.println("f(" + marker + ")");

    }

  }

  public class Mugs {

    Mug mug1;

    Mug mug2;

    {

      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)");

    }

    publis 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");

    }

  } /* Output:

  Mug(1)

  Mug(2)

  mug1 & mug2 initialized

  Mugs()

  new Mugs() completed

  Mug(1)

  Mug(2)

  mug1 & mug2 initialized

  Mugs(int)

  new Mugs(1) completed

  *///:~

  这里面的实例初始化子句:

  {

    mug1 = new Mug(1);

    mug2 = new Mug(2);

    System.out.println("mug1 & mug2 initialized");

  }

  看起来它与静态初始化子句一模一样,只不过少了static关键字,这种语法对于支持“匿名内部类”的初始化是必须的,但是它也使得你可以保证无论调用了哪个显示构造器,某些操作都会发生。从输出中可以看到实例初始化子句事在两个构造器之前执行的。

  

 

非静态实例初始化