类和对象的加载先后

静态的代码块,属性和方法都会在类加载时就开始加载了,它们的加载顺序按程序先后;当实例化一个类时,会先加载普通属性>构造块>构造函数>普通方法

静态块:用static申明,JVM加载类时执行,仅执行一次
构造块:类中直接用{}定义,每一次创建对象时执行,而且优先于构造函数执行(构造代码块中定义的是不同对象共性的初始化内容,给所有对象进行统一初始化;而构造函数是给对应的对象初始化)
执行顺序优先级:静态块>main()>构造块>构造方法>普通方法
public class B
{
    public static B t1 = new B();
    public static B t2 = new B();
    {
        System.out.println("构造块");
    }
    static
    {
        System.out.println("静态块");
    }
    public static void main(String[] args)
    {
        B t = new B();
    }
}
静态块按照声明顺序执行,所以先执行public static B t1 = newB();该语句创建对象,则又会调用构造块,输出构造块
最后main方法执行,创建对象,输出构造块
正确的结果是:构造块 构造块 静态块 构造块
class Demo {  
    int x;  
    static int y = 3;  
    // 静态代码块  
    static {  
        System.out.println("静态代码块");  
    }  
    // 定义构造代码块  
    {  
        System.out.println("我是构造代码块");  
        System.out.println("x=" + x);  
    }  
    //构造函数  
    public Demo() {  
    }  
      
    static void print() {  
        System.out.println("y=" + y);  
    }  
  
    void show() {  
        System.out.println("x=" + x + "  y=" + y);  
    }  
}  
  
class StaticDemo {  
    public static void main(String[] args) {  
        //类名调用print方法  
        Demo.print();  
        //创建对象  
        Demo d = new Demo();  
        //给成员变量x赋值  
        d.x = 10;  
        //用对象调用show方法  
        d.show();  
    }  
}  

静态代码块
y=3
我是构造代码块
x=0
x=10  y=3


高级案例
    import java.util.*;  
    class Bowl{  
        Bowl(int marker){  
            System.out.println("Bowl("+marker+")");  
        }  
        void f(int marker){  
            System.out.println("f("+marker+")");  
        }  
    }  
    class Table{  
        static Bowl b1 = new Bowl(1);  
        Table(){  
            System.out.println("Table()");  
            b2.f(1);  
        }  
        void f2(int marker){  
            System.out.println("f2("+marker+")");  
        }  
        static Bowl b2 = new Bowl(2);  
    }  
    class Cupboard{  
        Bowl b3 = new Bowl(3);  
        static Bowl b4 = new Bowl(4);  
        Cupboard(){  
            System.out.println("Cupboard()");  
            b4.f(2);  
        }  
        void f3(int marker){  
            System.out.println("f3("+marker+")");  
        }  
        static Bowl b5 = new Bowl(5);  
    }  
    public class Project10 {  
      
        public static void main(String[] args) {  
            // TODO Auto-generated method stub  
            System.out.println("Creating new Cupboard() in main");  
            new Cupboard();  
            t2.f2(1);  
            t3.f3(1);  
        }  
        static Table t2 = new Table();  
        static Cupboard t3 = new Cupboard();  
    }  

 Bowl(1)
Bowl(2)
Table()
f(1)
Bowl(4)
Bowl(5)
Bowl(3)
Cupboard()
f(2)
Creating new Cupboard() in main
Bowl(3)
Cupboard()
f(2)
f2(1)
f3(1)


原文地址:https://www.cnblogs.com/52circle/p/8945257.html