部分转载
属性、方法、构造方法和自由块都是类中的成员,在创建类的对象时,类中各成员的执行顺序:
1.父类静态成员和静态初始化快,按在代码中出现的顺序依次执行。2.子类静态成员和静态初始化块,按在代码中出现的顺序依次执行。
3. 父类的实例成员和实例初始化块,按在代码中出现的顺序依次执行。
4.执行父类的构造方法。
5.子类实例成员和实例初始化块,按在代码中出现的顺序依次执行。
6.执行子类的构造方法。
实验过程:
import java.io.OutputStream;
public class JParent
{
protected OutputStream out=System.out;
static
{
out.print
}
}
此时out处报错:
Cannot make a static reference to the non-static field out
建议将out改为static 意思就是说,static运行的时候out还没有呢
public class JChild extends JParent
{
protected OutputStream out=System.out;
static{
System.out.println("c's static");
}
public int i=test();
private int test()
{
((PrintStream)out).println("c's test");
return 123124;
}
public JChild()
{
// TODO Auto-generated constructor stub
((PrintStream)out).println("c's cons");
}
}
import java.io.OutputStream;
import java.io.PrintStream;
public class JParent
{
protected OutputStream out=System.out;
static
{
System.out.println("p's static");
}
public int i=test();
private int test()
{
((PrintStream)out).println("p's test");
return 123124;
}
public JParent()
{
// TODO Auto-generated constructor stub
((PrintStream)out).println("p's cons");
}
}public class JavaInitSeq
{
public static void main(String args[]){
JChild c=new JChild();
}
}
输出结果:
p's staticc's static
p's test
p's cons
c's test
c's cons
main中执行JParent c=new JChild();结果相同
main中执行JChild c=(JChild)new JParent();
输出:p's static
p's test
p's cons
Exception in thread "main" java.lang.ClassCastException: jav$a.JParent cannot be cast to jav$a.JChild
窥探到一些奇怪,全是parent的初始化。
推测:p跟c可能两个线程初始化,父线程执行会锁子线程。(仅是推测)