class Person{
public Person(int n){System.out.println(String.format("new Person(%s)",x));}
}
public class PersonTest(){
Person p1=new Person(1);
static Person p2=new Person(2);
static{
System.out.println("static code block");
}
{
System.out.println("no-static code block");
}
public PersonTest(){
System.out.println("new PersonTest()");
}
static Person p3=new Person(3);
Person p4=new Person(4);
public static void main(String[] args){
//
new PersonTest();
System.out.println("*************");
new PersonTest();
}
}
/** output
new Person(2)
static code block
new Person(3)
new Person(1)
non-static code block
new Person(4)
new PersonTest()
*************
new Person(1)
non-static code block
new Person(4)
new PersonTest()
**/
如果main方法中,什么都不做.只是调用static main()方法.
/** output
new Person(2)
static code block
new Person(3)
**/
从上面看出来,在不考虑继承的条件下,类中属性和构造函数的加载顺序如下:
(1)static 属性 / static 代码块 注意:有多个static属性和static代码块时,按声明顺序加载
(2)non-static 属性/ non-static 代码块 注意:有多个non-static属性和non-static代码块时,按声明顺序加载
(3)constructor构造函数
public Person(int n){System.out.println(String.format("new Person(%s)",x));}
}
public class PersonTest(){
Person p1=new Person(1);
static Person p2=new Person(2);
static{
System.out.println("static code block");
}
{
System.out.println("no-static code block");
}
public PersonTest(){
System.out.println("new PersonTest()");
}
static Person p3=new Person(3);
Person p4=new Person(4);
public static void main(String[] args){
//
new PersonTest();
System.out.println("*************");
new PersonTest();
}
}
/** output
new Person(2)
static code block
new Person(3)
new Person(1)
non-static code block
new Person(4)
new PersonTest()
*************
new Person(1)
non-static code block
new Person(4)
new PersonTest()
**/
如果main方法中,什么都不做.只是调用static main()方法.
/** output
new Person(2)
static code block
new Person(3)
**/
从上面看出来,在不考虑继承的条件下,类中属性和构造函数的加载顺序如下:
(1)static 属性 / static 代码块 注意:有多个static属性和static代码块时,按声明顺序加载
(2)non-static 属性/ non-static 代码块 注意:有多个non-static属性和non-static代码块时,按声明顺序加载
(3)constructor构造函数