代码块顺序执行的先后

代码的执行顺序一般为:静态代码块->普通代码块->构造快

1.在主类中

静态代码块在主类中,静态代码快优先于main()方法执行

      

class HelloA {
    public HelloA(){
        System.out.println("4.helloA!父类构造方法");
    }
    {
        System.out.println("3.父类非静态快");
    }
    static{
        System.out.println("1.父类静态块");
    }
}
public class HelloB extends  HelloA {
    public HelloB(){
        System.out.println("6.helloB!子类构造方法");
    }
    {
        System.out.println("5子类非静态快");
    }
    static{
        System.out.println("2.子类静态块");
    }
    public static void main(String[] args){
        System.out.println("====start===");
        new HelloB();
        new HelloA();
        System.out.println("===end===");
    }
}

2.在非主类中

静态代码块在非主类中,无论产生多少个实例化对象,静态代码块仅仅只执行一次 

          

public class TestSequence {
 public static void main(String[] args){
     new HelloC();
     new HelloC();
 }
}
class HelloC{

    {
        System.out.println("代码快");
    }
    static {
        System.out.println("1.静态块");
    }
    public HelloC(){
        System.out.println("2.构造块");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43240245/article/details/84729370
今日推荐