老王学java之代码块

代码1:

class Demo{
    {    // 直接在类中编写代码块,称为构造块
        System.out.println("1、构造块。") ;
    }
    public Demo(){    // 定义构造方法
        System.out.println("2、构造方法。") ;
    }
};
public class CodeDemo02{
    public static void main(String args[]){
        new Demo() ;        // 实例化对象
        new Demo() ;        // 实例化对象
        new Demo() ;        // 实例化对象
    }
};

执行结果:

代码2:

class Demo{
    {    // 直接在类中编写代码块,称为构造块
        System.out.println("1、构造块。") ;
    }
    static{    // 使用static,称为静态代码块
        System.out.println("0、静态代码块") ;
    }
    public Demo(){    // 定义构造方法
        System.out.println("2、构造方法。") ;
    }
};
public class CodeDemo03{
    static{        // 在主方法所在的类中定义静态块
        System.out.println("在主方法所在类中定义的代码块") ;
    }
    public static void main(String args[]){
        new Demo() ;        // 实例化对象
        new Demo() ;        // 实例化对象
        new Demo() ;        // 实例化对象
    }
};

执行结果2:

运行结果说明静态的代码块指产生一次。

原文地址:https://www.cnblogs.com/wanglei-134/p/3188216.html