java语言基础|如何在main方法前执行其他代码

xiaoxiao2021-02-27  202

在java中先执行静态类的方法和成员,再执行普通花括号内的方法,最后执行构造方法。 而java在加载类的时候会先加载静态快的代码并调用

public class Test { public Test() { System.out.println("constructor"); } static { System.out.println("static"); } { System.out.println("normal"); } public static void main(String[] args) { System.out.println("main"); }//这个代码输出为 static main } public class Test { public Test() { System.out.println("constructor"); } static { System.out.println("static"); } { System.out.println("normal"); } public static void main(String[] args) { Test test=new Test(); }//这个输出为static normal cinstructor }

java类的初始化顺序为 静态代码块内的变量 静态代码块(静态对象只初始化一次) 非静态代买快内的变量 非静态代码块(可能会初始化多次)

转载请注明原文地址: https://www.6miu.com/read-12646.html

最新回复(0)