今天起,日志开辟专栏,将专业学习的一些知识点记录下来。用BLOG记录似乎更加方便一些,权且当作学习笔记吧。 完整的初始化过程。 例:class con1{ public con1() { System.out.println("1"); } } class con2 extends con1{ String x="hello"; public con2() { System.out.println("2"); tt(); } public void tt() { System.out.println("a"+x); }} class con3 extends con2{ String x="hi"; public con3() { System.out.println("4"); tt(); } public void tt() { System.out.println("b"+x); } public static void main(String args[]) { con2 x = new con3(); x.tt(); System.out.println("Last is "+x.x); con3 y=(con3) x; System.out.println("Last is "+y.x); }}其执行过程如下。先执行new con3()。(1)new con3() 中无this(),那么又执行public con2()。1)public con2()中也无this(),又执行public con1()。 1、public con1()中也无this,执行Object的构造器。 2、显示初始化,无成员变量。 3、继续向下执行,输出1。2)显示初始化,执行x="hello";语句。3)继续向下执行,输出2执行tt(),因为tt已经被覆盖,因而执行的是子类的tt(),子类中因为x尚未显示初 始化,因而为null,显示bnull。(2)显示初始化,执行x="hi":语句。(3)继续向下执行,输出4。tt()执行被重载的方法,输出x的值为bhi。(4)继续执行main();1)x.tt(),执行被重载的方法,输出为bhi。2)输出x.x,变量无覆盖,显示为父类的Last is hello。3)将x转化为子类的con3类型。4)输出y.x,显示为子类的Last is hi。执行结果为:12bnull4bhibhiLast is helloLast is hi

评论