子类初始化时,父类构造器调用自身和子类都有的方法,会执行谁?

2014-11-24 11:30:13 · 作者: · 浏览: 4

[java]
class Pa {
String color="黑白";
public Pa() {
System.out.println("Pa"+"@"+Test.NUM++);
print();
}
public void print(){
System.out.println(color+"@"+Test.NUM++);
}

}
class Son extends Pa{
String color = "彩色";
String toy = "我有弹弓";
public Son() {
System.out.println("Son"+"@"+Test.NUM++);
}
public void print(){
System.out.println(toy+"@"+color+"@"+Test.NUM++);
}
}
/**
*
*/
public class Test{
public static int NUM = 0;
public static void main(String[] args) {
new Son();
// new Pa();
}
}

class Pa {
String color="黑白";
public Pa() {
System.out.println("Pa"+"@"+Test.NUM++);
print();
}
public void print(){
System.out.println(color+"@"+Test.NUM++);
}

}
class Son extends Pa{
String color = "彩色";
String toy = "我有弹弓";
public Son() {
System.out.println("Son"+"@"+Test.NUM++);
}
public void print(){
System.out.println(toy+"@"+color+"@"+Test.NUM++);
}
}
/**
*
*/
public class Test{
public static int NUM = 0;
public static void main(String[] args) {
new Son();
// new Pa();
}
} * 父类Pa构造方法中调用了print(),而子类Son也重写了print();
* 在new Son()初始化的过程中,子类的成员color和toy都尚未完成赋值,
* 但是:还是会将方法动态绑定到子类的print()
* 这点值得注意,现实中很可能因此出现bug。切记!

这是程序输出:


Pa@0
null@null@1
Son@2