Execution order of constructors, ordinary code blocks, static code blocks, and static methods in java

static methods, static blocks, building blocks

 

public class ParentClass {
	static{
		System.out.println("I am the static code block of the parent class");
	}
	{
		System.out.println("I am the normal code block of the parent class");
	}
	public ParentClass(){
		System.out.println("I am the constructor of the parent class");
	}
	public static void method(){
		System.out.println("Static method modified by static");
	}
        public static void main(String[] args) {
		ParentClass parentClass = new ParentClass();
		parentClass.method();
	}
}
The result is:
    I am the static code block of the parent class
    I am a normal code block of the parent class
    I am the constructor of the parent class
    static modified by static

 

 

public class ChildrenClass extends ParentClass {

	static{
		System.out.println("I am the static code block of the subclass");
	}
	{
		System.out.println("I am a normal code block of a subclass");
	}
	
	public ChildrenClass(){
		System.out.println("I am the constructor of the subclass");
	}
	public static void method(){
		System.out.println("The static method of the subclass is modified by static");
	}
	@SuppressWarnings("static-access")
	public static void main(String[] args) {
		ParentClass parentClass = new ChildrenClass();
		parentClass.method();
	}
}
The result is:
     I am the static code block of the parent class
     i'm a static code block of a subclass
     I am a normal code block of the parent class
     I am the constructor of the parent class
     I'm a normal code block of subclasses
     I am the constructor of the subclass
     A static method in a subclass that is modified by static

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326133792&siteId=291194637