父类构造多态调用的陷阱

 class Parent {
  public Parent() {
   callMethod();
  }

  public void callMethod() {
   System.out.println("我是父类里的方法");
  }
 }
 class Child extends Parent{
  int a;
  public Child() {
   /**
    * 这里是我猜想---
    * 编译器编译的时候在这里插入
    * super();
    * 因为super()只是sun用于引用本类的父类一个标志,
    * 其语义应该是类似方法的调用,我们应该知道,在类里,除了static方法外,
    * 其他的方法,编译器在处理的时候都会秘密加入this,this代表当前对象,
    * 从而方法里的方法调用或变量 知道它自己是属于谁的。
    * super属于子类,super()调用的时候是子类中调用父类中的构造,super()可以看做类似方法的东西
    * 编译器会为其传入当前对象this,
    * 因此Parent() {callMethod();},内传入的this是Child的对象
    * 所以多态调用的是Child里的方法,
    * 这样就可以解释清楚为什么打印的时
    * ----我是子类里的方法0------------了
    *
    *由此而引发的问题是不可预料的!!!!!!!!!!!!!!!1
    *你如果在父类构造函数里调用了子类里方法,
    *而且在父类初始化的时候,子类不可能初始化,所以a是显示0
    *可以想象,变量此时会被初始化null或者0之类的,你的程序会因此而非常糟糕,排错也不是那么轻松
    *所以要注意!!!!!!!!!!!!!!!
    *
    *
    *from sunflower 2008-9-28

    */
   a=10;
   
  }
  public void callMethod() {
   System.out.println("我是子类里的方法"+a);
  }
 }
 public class Test {
  public static void main(String[] args) {
   new Child();
  }
 }

你可能感兴趣的:(sun)