Java中构造方法的调用顺序
程序员文章站
2022-05-14 09:25:08
...
顺序:
1-先执行内部静态对象的构造方法,如果有多个按定义的先后顺序执行;静态对象在构造的时候也是也先执行其内部的静态对象;
2-一直从基类开始调用;
3-按声明顺序将成员引用对象变量初始化;
4-最后调用自身的构造方法。
看代码再理解下:
package Ch5;
class Meal{
Meal(){
System.out.println(" Meal");
}
}
class Bread{
Bread(){
System.out.println("Bread");
}
public sta s=new sta();
}
class Cheese{
Cheese(){
System.out.println("Cheese");
}
}
class Lettuce{
Lettuce(){
System.out.println("Lettuce");
}
}
class Lunch extends Meal{
Lunch(){
System.out.println("Lunch");
}
}
class Portable extends Lunch{
Portable(){
System.out.println("Portable");
}
}
class Sandwich extends Portable{
Sandwich(){
System.out.println("Sand");
}
}
class sta{
sta(){
System.out.println("静态对象");
}
}
public class T_init2 extends Sandwich{
Bread b=new Bread();
Cheese c=new Cheese();
Lettuce l=new Lettuce();
T_init2(){
System.out.println("start");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
T_init2 t=new T_init2();
}
}
类之间的关系:
meal<-lunch<-portable<-sandwich<-T-init2
bread(里面有静态对象sta)、cheese、lettuce并列
看结果:
Meal
Lunch
Portable
Sand 2-从基类开始一步步
静态对象 1-静态优先
Bread
Cheese
Lettuce 3-按声明顺序
start 4-调用自身