初始化

  • 初始化顺序
    在类的内部,变量的定义先后顺序决定了初始化的顺序。即使变量定义散布于方法定义之间。他们任就会在任何方法(包括构造器)被调用之前得到初始化
 public class init {
    public static void main(String[] args) {
        House house = new House();
        house.print();
    }
}
class Window{
    Window(int math){
        System.out.println("Window:\t"+math);
    }
}
class House{
    Window window1 = new Window(1);
    House(){
        System.out.println("House");
        window3 = new Window(4);
    }
    Window window2 = new Window(2);
    void print(){
        System.out.println("print()");
    }
    Window window3 = new Window(3);
}

结果:
Window: 1
Window: 2
Window: 3
House
Window: 4
print()

  • 静态变量的初始化
    无论创建多少个变量 静态数据都只占用一份存储区域 static 不能应用于局部变量 因此他只能作用于域
 public class InitStatic {
    public static void main(String[] args) {
        System.out.println("start print method Cupboard()");
        new Cupboard();
        System.out.println("start print method Cupboard()");
        new Cupboard();
    }
    //首先执行
    static Table table = new Table();
    static Cupboard cupboard = new Cupboard();
} 
class Bowl{
    Bowl(int math){
        System.out.println("Bowl()\t"+math);
    }
    void print1(int math){
        System.out.println("print()\t"+math);
    }
}
class Table{
    static Bowl bowl1 = new Bowl(1);
    Table(){
        System.out.println("Table()");
    }
    void print2(int math){
        System.out.println("print2()\t"+math);
        bowl2.print1(1);
    }
    static Bowl bowl2 = new Bowl(2);
}
class Cupboard{
    Bowl bowl3 = new Bowl(3);
    static Bowl bowl4 = new Bowl(4);
    Cupboard(){
        System.out.println("Cupboard()");
        bowl4.print1(2);
    }
    void print3(int math){
        System.out.println("print3()\t"+math);
    }
    static Bowl bowl5 = new Bowl(5);
}

结果是:
Bowl() 1
Bowl() 2
Table()
Bowl() 4
Bowl() 5
Bowl() 3
Cupboard()
print() 2
start print method Cupboard()
Bowl() 3
Cupboard()
print() 2
start print method Cupboard()
Bowl() 3
Cupboard()
print() 2

  • 显式的静态初始化
    java允许将多个静态初始化动作组织成一个特殊的“静态子句”(也叫静态代码块),与其他的静态初始化动作一样,这段代码仅执行一次:当首次生成这个类的对象时,或者首此访问属于哪个类的静态数据成员时
class Cup{
    Cup(){
          System.out.println("Cup()");
}
}
 class Cups{
      static Cup cup1;
      static Cup cup2;
       static{
        cup1 = new Cup(1);
         cup1 = new Cup(2);
    }

}
  • 非静态实例实例初始化(代码块初始化)
    与静态初始化一样,只是少了一个static,代码块会在构造器执行之前先执行
class Cup{
    Cup(){
          System.out.println("Cup()");
}
}
 class Cups{
      Cup cup1;
      Cup cup2;
       {
        cup1 = new Cup(1);
         cup1 = new Cup(2);
      }

}

你可能感兴趣的:(初始化)