变量初始化的顺序

变量初始化的顺序问题

看java编程思想,在变量初始化过程中有点绕,摘出来,记录下。

/**
 * 定义一个bowl类
 *
 * @author 吧嘻小米
 * @since 1.0-SNAPSHOT
 */
public class Bowl {
    public Bowl(int marker) {
        System.out.println("Bowl(" + marker + ")");
    }

    public void f1(int marker) {
        System.out.println("f1(" + marker + ")");
    }
}
/**
 * 定义一个cupboard类
 *
 * @author 吧嘻小米
 * @since 1.0-SNAPSHOT
 */
public class Cupboard {
    static Bowl bowl4 = new Bowl(4);
    static Bowl bowl5 = new Bowl(5);
    Bowl bowl3 = new Bowl(3);

    public Cupboard() {
        System.out.println("cupboard()");
        bowl4.f1(2);
    }

    public void f3(int marker) {
        System.out.println("f3(" + marker + ")");
    }
}

/**
 * 定义table类
 *
 * @author 吧嘻小米
 * @since 1.0-SNAPSHOT
 */
public class Table {
    static Bowl bowl1 = new Bowl(1);
    static Bowl bowl2 = new Bowl(2);

    public Table() {
        System.out.println("Table()");
        bowl2.f1(1);
    }

    public void f2(int marker) {
        System.out.println("f2(" + marker + ")");
    }
}

/**
 * 变量初始化的顺序演示
 *  * @author 吧嘻小米
 * @since 1.0-SNAPSHOT
 */
public class StaticInitialization {

    static Table table = new Table();
    static Cupboard cupboard = new Cupboard();

    public static void main(String[] args) {
        System.out.println("create new Cupboard() in main");
        new Cupboard();
        System.out.println("Create new Cupboard() in main");
        new Cupboard();
        table.f2(1);
        cupboard.f3(1);
    }/*Output:
     Bowl(1)
     Bowl(2)
     Table()
     f1(1)
     Bowl(4)
     Bowl(5)
     Bowl(3)
     cupboard()
     f1(2)
     create new Cupboard() in main
     Bowl(3)
     cupboard()
     f1(2)
     Create new Cupboard() in main
     Bowl(3)
     cupboard()
     f1(2)
     f2(1)
     f3(1)
    *///:~
}

小结:

  • 变量的初始化顺序,静态变量–>其他变量;
  • 只有当一个变量完成全部的初始化(包括静态变量的初始化,构造方法的完成等)才会顺序执行下一个变量的初始化;
  • 静态变量只会初始化一次,非静态变量会被初始化多次;
  • 静态变量只有在被调用时才会初始化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值