Java类的加载与初始化

时间:2023-02-16 22:36:15

Java类的加载与初始化步骤如下所述:

  1. 从基类开始进行静态成员初始化;

  2. 执行main()方法;

  3. 按照声明顺序先调用基类成员的初始化方法,再调用基类构造器;

  4. 按照步骤3对导出类先进行成员初始化,再调用构造器。

参照以下程序:

package polymorphism;

    class Meal {    
        private static Bread bread = new Bread();
        private Cheese cheese = new Cheese();
        Meal() {
            System.out.println("Meal()");
        }
    }

    class Bread {
        Bread() {
            System.out.println("Bread()");
        }
    }

    class Cheese {
        Cheese() {
            System.out.println("Cheese()");
        }
    }

    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();
        private Cheese c = new Cheese();
        private Sandwich() {
            System.out.println("Sandwich()");
        }

    public static void main(String[] args) {
        System.out.println("main()");
        new Sandwich();
    }
}

输出为:

Bread()
main()
Cheese()
Meal()
Lunch()
PortableLunch()
Bread()
Cheese()
Sandwich()