我在网上搜索了很长时间。但没用。请帮助或尝试提供一些想法如何实现此目的?为什么结果不是在第一个打印“int main”?我想知道的是为什么这个程序的结果如下?预先感谢。静态方法的执行顺序(JAVA)
超静块
静块4
在主
超级构造
构造
class StaticSuper {
static {
System.out.println("super static block");
}
StaticSuper() {
System.out.println("super constructor");
}
}
public class StaticTests extends StaticSuper {
static int rand;
//static initialise
static {
rand = (int) (Math.random() * 6);
System.out.println("static block " + rand);
}
StaticTests() {
System.out.println("constructor");
}
public static void main(String[] args) {
System.out.println("in main");
StaticTests st = new StaticTests();
}
}
谢谢您的回答sincerely.I已经看了你的文章,我有一个问题:我们所说的构造函数之前子类的non_field初始化子类,是不是?我们为什么不能从构造函数中调用non_field?我不理解它。 – Manhand
我对此感到很抱歉,我输入的问题是错误的。问题是为什么我们不应该从构造函数中调用非final方法(。我已经阅读过您的文章,并且有一个问题:子类的non_field是在我们调用子类的构造函数之前进行初始化,是不是?我们为什么不能从构造函数中调用非final方法?我不明白) – Manhand
@Manhand我用代码更新了我的答案,以解释为什么它不建议在构造函数中调用非final方法。核实。 – SkrewEverything