继承与初始化和构造器的调用

来源:互联网 发布:淘宝欧时力有正品吗 编辑:程序博客网 时间:2024/06/07 17:22

调用构造器要遵循以下顺序:
1、调用基类构造器。这个步骤会不断反复递归下去,首先是构造这种层次结构的根,然后是下一层导出类,等等,直到最底层的导出类。
2、按声明顺序调用成员的初始化方法。
3、调用导出类构造器的主体。

继承与初始化
请看下例:

class Insect {private int i = 9;protected int j;// protected static int j; 上转型时 j 不再初始化,为39Insect() {System.out.println("i=" + i + ",j=" + j);j = 39;}private static int x1 = printInit("static Insect.x1 initialized");static int printInit(String s) {System.out.println(s);return 47;}}public class Beetle extends Insect {private int k = printInit("Beetle.k initialized");public Beetle() {System.out.println("k=" + k);System.out.println("j=" + j);}private static int x2 = printInit("static Insect.x2 initialized");public static void main(String[] args) {System.out.println("Beetle constructor");Beetle b = new Beetle();System.out.println();Insect a = new Beetle();}}

运行结果:

static Insect.x1 initializedstatic Insect.x2 initializedBeetle constructori=9,j=0Beetle.k initializedk=47j=39i=9,j=0Beetle.k initializedk=47j=39


构造器的调用顺序
请看下例:

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();private Lettuce l = new Lettuce();private Cheese c = new Cheese();public Sandwich() {System.out.println("Sandwich()");}public static void main(String[] args) {new Sandwich();}}

运行结果:

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




0 0
原创粉丝点击