初学者问个有关对象初始化的问题,谢谢
class Meal
{
Meal()
{
System.out.println( "Meal() ");
}
}
class Bread
{
Bread()
{
System.out.println( "Bread() ");
}
}
class Cheese
{
Cheese()
{
System.out.println( "Cheese() ");
}
}
class Lettuce
{
Lettuce()
{
System.out.println( "Lettuce() ");
}
}
class Lunch extends Meal
{
Lunch()
{
System.out.println( "Lunch() ");
}
}
class PortableLunch extends Lunch
{
PortableLunch()
{
System.out.println( "PortableLunch() ");
}
}
public class Sandwich extends PortableLunch
{
private Bread b=new Bread(); //1
private Cheese c=new Cheese(); //2
private Lettuce l=new Lettuce(); //3
public Sandwich()
{
System.out.println( "Sandwich() ");
}
public static void main(String[] args)
{
new Sandwich();
}
}
输出结果为:
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Lettuce()
Sandwich()
我的问题是:1 2 3对象不是应该在调用Sandwich()构造函数之前得到初始化吗,我觉得输出结果应为
Bread()
Cheese()
Lettuce()
Meal()
Lunch()
PortableLunch()
Sandwich()
为什么会有问题?
------解决方案--------------------子类再初始化自己的属性之前会优先初始化父类的属性~~~
------解决方案--------------------在JAVA编程思想里有初始化顺序的讲解
实例化子类时,先初始化父类属性,你类构造方法.
------解决方案--------------------在父类里再写一个带参数的构造方法就能说明问题了
class FatherClass {
public FatherClass() {
System.out.println( "FatherClass ");
}
public FatherClass(int i) {
System.out.println( "FatherClass " + i);