public class Person {
Person person;
public static void main(String[] args) {
Person a = new Person();
}
{
System.out.println("aaaa");
person = new Person();
}
public Person() {
System.out.println(person);
}
}
在程序块里打印一句话
输入:
aaaa
aaaa
aaaa
aaaa
aaaa
aaaa
aaaa
aaaaException in thread "main" java.lang.StackOverflowError
at sun.nio.cs.ext.DoubleByteEncoder.encodeArrayLoop(DoubleByteEncoder.java:126)
at sun.nio.cs.ext.DoubleByteEncoder.encodeLoop(DoubleByteEncoder.java:189)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:544)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:252)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:106)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:190)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:111)
at java.io.PrintStream.newLine(PrintStream.java:495)
at java.io.PrintStream.println(PrintStream.java:757)
at Test.Person.<init>(Person.java:12)
说明先执行的是代码块的代码,再调用构造方法
假如这样改动代码
public class Person {
static Person person = null;
public static void main(String[] args) {
Person a = new Person();
}
static{
System.out.println("aaaa");
person = new Person();
}
public Person() {
System.out.println(person);
}
}
输出结果:
aaaa
null
Test.Person@de6ced
为什么会出先空值呢?