package com.me;
public class Parent {
public String name="parent name";
{
System.out.println("parent common 语句块");
}
static {
System.out.println("parent static 语句块");
}
public Parent(){
System.out.println(this.name);
this.show();
}
public void show(){
System.out.println("here "+this.name);
System.out.println("Parent common show");
}
}
package com.me;
public class ChildA extends Parent{
public static String name="CA";
static {
System.out.println("childa static 语句块");
}
{
System.out.println("childa common 语句块");
}
public ChildA(){
System.out.println(this.name);
this.show();
}
public void show(){
System.out.println("childA common show");
}
}
package com.me;
public class ChildB extends ChildA{
public String name="CB";
public C c=new C();
static {
System.out.println("childb static 语句块");
}
{
System.out.println("childb common 语句块");
}
public ChildB(){
System.out.println(this.name);
this.show();
D d=new D();
}
public void show(){
System.out.println("childB common show");
}
}
package com.me;
public class C {
public String name="C";
public C(){
System.out.println(this.name);
}
}
package com.me;
public class D {
public String name="D";
public D(){
System.out.println(this.name);
}
}
package com.me;
public class Test {
public static void main(String[] args){
ChildB cb=new ChildB();
}
}
一共六个类parent,childa,childb,c,d,test
public class ChildA extends Parent
public class ChildB extends ChildA
c,d,test独立
ChildB的属性中public C c=new C();
ChildB的构造方法中D d=new D();
好了,明白了类之间的关系就写出打印结果了,如下:
parent static 语句块
childa static 语句块
childb static 语句块
parent common 语句块
parent name
childB common show
childa common 语句块
CA
childB common show
C
childb common 语句块
CB
childB common show
D
总结:
执行的顺序
父类------>子类
各个类中的静态语句块(匿名方法)
普通(非静态)语句块,属性的初始化都在构造方法前执行
普通(非静态)语句块,属性按顺序由上到下一次执行
Parent类,ChildA,ChildB存在继承关系,并且三个类中都有
方法show,this.show执行的始终是子类中的show方法,若ChildB中
无show则执行ChildA中的show方法,若ChildB中也没有则执行Parent
中的方法,若ChildB中没有ChildA中有则执行Parent中的(废话,呵呵)
到此"子类父类方法与属性的调用"系列到此结束,不知坚持看完这四篇
文章的朋友晕了没,呵呵
睡觉去了。。。