Java static code block, and code block execution order constructor

Analyzed according to the following procedure

The definition of a parent class

package sas.LearnJava;

public class ExcuteOrderTest {
    {
        System.out.println("我是在父类开始的普通代码块!");
    }

    public ExcuteOrderTest() {
        System.out.println("我是父类的无参构造函数!");
    }

    public void showSomething() {
        System.out.println("我是父类中定义的方法!");
    }

    static {
        System.out.println("我是在父类中静态的代码块!");
    }
}

Define a subclass

package sas.LearnJava;

public class SubExcuteOrderTest extends ExcuteOrderTest {
    static {
        System.out.println("我是在子类中的静态代码块!");
    }

    public SubExcuteOrderTest() {
        System.out.println("我是子类的无参构造函数!");
    }
    @Override
    public void showSomething() {
        System.out.println("我是子类中定义的方法!");
    }

    public static void test() {
        System.out.println("子类中的静态测试方法");
    }

    {
        System.out.println("我是在子类结束的普通代码块!");
    }
}

A write subclasses using the demo

package sas.LearnJava;

public class ExcuteOrderDemo {
    public static void main(String[] args) {
        System.out.println("创建第一个对象");
        SubExcuteOrderTest subExcuteOrderTest1 = new SubExcuteOrderTest();
        System.out.println("创建第二个对象");
        SubExcuteOrderTest subExcuteOrderTest2 = new SubExcuteOrderTest();
    }
}
创建第一个对象
我是在父类中静态的代码块!
我是在子类中的静态代码块!
我是在父类开始的普通代码块!
我是父类的无参构造函数!
我是在子类结束的普通代码块!
我是子类的无参构造函数!
创建第二个对象
我是在父类开始的普通代码块!
我是父类的无参构造函数!
我是在子类结束的普通代码块!
我是子类的无参构造函数!

From the results it can be run a few:

  • When you create an object class is executed in the parent class code block and the default constructor with no arguments, and then execute the code blocks and their constructor
  • Static code block, when executed determines the order of code blocks, and non-static constructors, and irrespective of the position in the program
  • Subclass static block of code will be executed after the static block of code execution parent
  • Static code block is executed only once, ordinary block of code to create an object with re-initialized
package sas.LearnJava;

public class ExcuteOrderDemo {
    public static void main(String[] args) {
        SubExcuteOrderTest.test();
    }
}
我是在父类中静态的代码块!
我是在子类中的静态代码块!
子类中的静态测试方法

When not creating an object directly call the static method of the class, static code block will only execute the parent class and subclass

Guess you like

Origin www.cnblogs.com/sasworld/p/11515616.html