zoukankan      html  css  js  c++  java
  • Java构造方法 代码块 static 执行顺序

    class Demo {
        static Demo demo1 = new Demo();
        static Demo demo2 = new Demo();
        
        {
            System.out.println("构造代码块");   
        }
        
        static {
            System.out.println("静态代码块");  
        }
        
        public Demo() {
            System.out.println("构造方法");  
        }
        
        public static void main(String[] args) {
            Demo demo1 = new Demo();
        }
    }
    /*
    问:
        代码执行流程!!!
    */

    执行结果

    构造代码块
    构造方法
    构造代码块
    构造方法
    静态代码块
    构造代码块
    构造方法


    //静态属性之间按顺序执行
    1.执行static Demo demo1 = new Demo();
    2.构造代码块:初始化当前类所有的类对象,只要【使用new + 构造方法创建当前类对象】,就一定会执行构造代码块中的内容


    class Demo {
        static int num1 = 10;
        static int num2 = 20;
        
        {
            System.out.println("构造代码块");
        }
        
        static {
            num1 = 20;
            num2 = 100;
        }
        
        public Demo() {
            System.out.println("构造方法");
        }
        
        public static void main(String[] args) {
            new Demo();
        }
    }
    /*
    代码执行效果已经num1和num2的值是多少
    */
    构造代码块
    构造方法
    20
    100

    // 每行代码后的“//1”为整个程序的调用流程
    package
    randy2; class Bowl { public Bowl(int marker) {//3//6//15//18//21//30//39 System.out.println("Bowl(" + marker + ")");//4//7//16//19//22//31//40 } public void f1(int marker) { System.out.println("f1(" + marker + ")");//11//26//35/44 } } class Table { static Bowl bowl1 = new Bowl(1);//2 public Table() {//8 System.out.println("Table()");//9 bowl2.f1(1);//10 } public void f2(int marker) { System.out.println("f2(" + marker + ")");//46 } static Bowl bowl2 = new Bowl(2);//5 } class Cupboard {//13 Bowl bowl3 = new Bowl(3);//20//29//38 static Bowl bowl4 = new Bowl(4);//14 public Cupboard() {//23//32//41 System.out.println("Cupboard()");//24/33//42 bowl4.f1(2);//25//34//43 } public void f3(int marker) { System.out.println("f3(" + marker + ")");//48 } static Bowl bowl5 = new Bowl(5);//17 } public class StaticInit { public static void main(String[] args) { System.out.println("Creating new Cupboard() int main");//27 new Cupboard();//28 System.out.println("Creating new Cupboard() int main");//36 new Cupboard();//37 table.f2(1);//45 cupboard.f3(1);//47 } static Table table = new Table();//1 static Cupboard cupboard = new Cupboard();//12 }
    Bowl(1)
    Bowl(2)
    Table()
    f1(1)
    Bowl(4)
    Bowl(5)
    Bowl(3)
    Cupboard()
    f1(2)
    Creating new Cupboard() int main
    Bowl(3)
    Cupboard()
    f1(2)
    Creating new Cupboard() int main
    Bowl(3)
    Cupboard()
    f1(2)
    f2(1)
    f3(1)
  • 相关阅读:
    ACCESS中默认值要填双引号
    错误一直找不到
    员工自行车的摆放处
    连接占线导致另一个hstmt
    去裕利面试
    路上又一见闻
    企业的形象
    骏泰面试感觉
    IE 标点符号输入不顺的原因
    C Primer Plus(十七)
  • 原文地址:https://www.cnblogs.com/raising/p/12838614.html
Copyright © 2011-2022 走看看