总体上先父后子
具体体现于
1、先static,按顺序执行(无论static位于什么位置,都现执行)
2、再非static
3、再构造
|
package
com.test.part7;
public
class
Test_2 {
/**
*
@param
args
*/
public
static
void
main(String[] args) {
new
A();
}
}
class
A
extends
C {
E
e
=
new
E();
A() {
System.
out
.println(
"A constructor"
);
}
static
D
d
=
new
D();
}
class
B {
B() {
System.
out
.println(
"B constructor"
);
}
}
class
C {
B
b
=
new
B();
C() {
System.
out
.println(
"C constructor"
);
}
}
class
D {
D() {
System.
out
.println(
"D constructor"
);
}
}
class
E {
E() {
System.
out
.println(
"E constructor"
);
}
}
|
D constructor
B constructor
C constructor
E constructor
A constructor
|
重要例子[
现加载含main的类,加载过程中会现加载static块如果有父类,那按先父到子加载),再调用main方法,进行里面的代码初始化
new MyClass(),然后进行MyClass的加载,myClass继承于Test,
Test在加载的时候已经加载了static的内容,剩下加载非static的内容]
public
class
Test {
Person person =
new
Person(
"Test"
);
static
{
System.out.println(
"test static"
);
}
public
Test() {
System.out.println(
"test constructor"
);
}
public
static
void
main(String[] args) {
new
MyClass();
}
}
class
Person{
static
{
System.out.println(
"person static"
);
}
public
Person(String str) {
System.out.println(
"person "
+str);
}
}
class
MyClass
extends
Test {
Person person =
new
Person(
"MyClass"
);
static
{
System.out.println(
"myclass static"
);
}
public
MyClass() {
System.out.println(
"myclass constructor"
);
}
}
|