Java Constructors - Order of execution in an inheritance hierarchy

后端 未结 5 1220
予麋鹿
予麋鹿 2020-12-15 17:49

Consider the code below

  class Meal {
    Meal() { System.out.println(\"Meal()\"); }
  }

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


        
5条回答
  •  长情又很酷
    2020-12-15 18:26

    private Bread b = new Bread();
    private Cheese c = new Cheese();
    private Lettuce l = new Lettuce();
    

    These initializers are put into the Sandwich constructor by the compiler after the super call to it's parent class.

    If these were static, then they would happen first, because static initializers happen on class load.

提交回复
热议问题