以例题分析:
class Meal{
public Meal(){
System.out.println("meal()");
}
}
class Lunch extends Meal{
public Lunch(){
System.out.println("Lunch()");
}
}
class Vagetable{
public Vagetable(){
System.out.println("Vategable()");
}
}
class Potato extends Vagetable{
public Potato(){
System.out.println("Potato()");
}
}
class Tomato extends Vagetable{
public Tomato(){
System.out.println("Tomato()");
}
}
class Meat{
public Meat(){
System.out.println("Meat()");
}
}
class SandWish extends Lunch{
Potato p=new Potato();
Meat m=new Meat();
Tomato t=new Tomato();
public SandWish(){
System.out.println("SandWish()");
}
}
class F{
public static void main(String[]args){
SandWish s=new SandWish();
}
}
打印结果:
meal()
Lunch()
Vategable()
Potato()
Meat()
Vategable()
Tomato()
SandWish()
创建对象流程分析:
总结:
java有继承关系的对象创建过程规则(类似无继承创建对象过程):
- 给父类/子类属性分配空间,给父类/子类属性赋默认值;
- 给父类属性赋初始值;
- 利用父类构造方法给父类属性再次赋值;
- 给子类属性赋初始值;
- 利用子类构造给子类属性再次赋值;
核心思想:先创建父类对象才能创建子类对象;