当前位置:网站首页>Static code block vs construction code block

Static code block vs construction code block

2022-06-27 08:31:00 C_ x_ three hundred and thirty

class A {
    public A() {
        System.out.println("class A");
    }
    { System.out.println("I'm A class"); } 
    static { System.out.println("class A static"); }
}
public class B extends A {
    public B() {
        System.out.println("class B");
    }
    { System.out.println("I'm B class"); }
    static { System.out.println("class B static"); }
    
    public static void main(String[] args) { 
 new B(); 
class A static
class B static
I'm A class
class A
I'm B class
class B

When new When an object

If there are static code blocks

The system will automatically help you execute the static code block first

If A Inherited B also A,B There are static code blocks

When you new A() when ,

The system will automatically execute first B The static code block of is executing A Static code block

Then suppose B And building blocks of code , Then finish the execution A,B After the static code block of

I'll do it again B The construction code block of , And then in the B Construction method of

And then in the A The construction code block of , And then in the A Construction method of

原网站

版权声明
本文为[C_ x_ three hundred and thirty]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270823529488.html