Java 静态代码块和非静态代码块

参考:http://uule.iteye.com/blog/1558891

Java中的静态代码块是在虚拟机加载类的时候,就执行的,而且只执行一次。如果static代码块有多个,JVM将按照它们在类中出现的先后顺序依次执行它们,每个代码块只会被执行一次。

非静态代码块是在类new一个实例的时候执行,而且是每次new对象实例都会执行。

代码的执行顺序

  1. 主调类的静态代码块
  2. 对象父类的静态代码块
  3. 对象的静态代码块
  4. 对象父类的非静态代码块
  5. 对象父类的构造函数
  6. 对象的非静态代码块
  7. 对象的构造函数

示例代码

public class StaticBlockTest1 {

    //主调类的非静态代码块
    {
        System.out.println("StaticBlockTest1 not static block");
    }
    //主调类的静态代码块
    static {
        System.out.println("StaticBlockTest1 static block");
    }

    public StaticBlockTest1(){
        System.out.println("constructor StaticBlockTest1");
    }

    public static void main(String[] args) {
        Children children = new Children();
        children.getValue();
    }

}


class Parent{

    private String name;
    private int age;

    //父类无参构造方法
    public Parent(){
        System.out.println("Parent constructor method");
        {
            System.out.println("Parent constructor method--> not static block");
        }
    }
    //父类的非静态代码块
    {
        System.out.println("Parent not static block");
        name = "zhangsan";
        age = 50;
    }
    //父类静态代码块
    static {
        System.out.println("Parent static block");
    }

    //父类有参构造方法
    public Parent(String name, int age) {
        System.out.println("Parent constructor method");
        this.name = "lishi";
        this.age = 51;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

class Children extends Parent{
    //子类静态代码块
    static {
        System.out.println("Children static block");
    }

    //子类非静态代码块
    {
        System.out.println("Children not static block");
    }

    //子类无参构造方法
    public Children(){
        System.out.println("Children constructor method");
    }


    public void getValue(){
        //this.setName("lisi");
        //this.setAge(51);
        System.out.println(this.getName() + this.getAge());
    }
}

输出结果

StaticBlockTest1 static block   //主调类的静态代码块
Parent static block             //父类的静态代码块
Children static block           //子类的静态代码块
Parent not static block         //父类的非静态代码块
Parent constructor method       //父类的构造函数
Parent constructor method--> not static block
Children not static block       //主调类的非静态代码块
Children constructor method     //主调类的构造函数
zhangsan50                      //主调main方法

总结:

  1. 按照前面提到的顺序执行
  2. 子类定义无参构造方法,调用的父类也是无参构造方法
  • 6
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值