class Father
{
int m=5;
public Father(){this.show();}
void show(){System.out.println("父");}
}
class Child1 extends Father
{
int m=10;void show(){System.out.println(m);}
}
class Child2 extends Father
{void show(){System.out.println(m);}
}
class Test
{
public static void main(String args[])
{
Father n=new Child1();Father n1=new Child2();}
}

解决方案 »

  1.   

    因为child1和child2中均没有自己的构造器,所以创建对象时调用的是父类Father中的构造器。但是由于创建的对象(即new的对象)是子类的对象,所以它虽然构造器调用的是父类中的,但是this.show()却调用的是子类中的show()方法,this表示当前对象(即指子类对象)。child1输出0,child1中声明的属性m覆盖了父类中的属性,故输出的值为0.而child输出5是因为它继承了父类中的m故输出的值为5.
      

  2.   

    1.子类的域可以与父类同名。
      比如:Child1 c1=new Child1();
      c1会有两个int型的域:super.m和m(也就是this.m)。
    2.构造子类对象的时候,会先调用父类的构造方法,对继承自父类的域进行初始化,然后再对子类定义的域
      进行初始化。
      可以用下面的代码验证这个过程:
      public class Test{
    public static void main(String args[])
    {
    //执行Father()==>Child1.show():此时父类的构造方法还未结束,子类的域m还没有初始化
    Father n1=new Child1();
    Father n2=new Child2();
    }
    }class Father{
    int m=5;

    public Father(){
    System.out.println("father constructor start");
    this.show();
    System.out.println("father constructor end");
    }

    void show(){
    System.out.println("father show");
    System.out.println("父");
    }
    }class Child1 extends Father{
    int m = 6;

    public Child1(){
    System.out.println("child1 constructor start");
    this.show();
    System.out.println("child1 constructor end");
    }

    void show(){
    System.out.println("child1 show start");
    System.out.println(m);
    System.out.println("child1 show end");
    }
    }class Child2 extends Father{
    void show(){System.out.println(m);}
    }
      

  3.   


    看看这顺序,在父类构造方法没完成时 子类m=10其实还同有执行到,也就是给值也没有用,打印出来的应该是int的默认值0
      

  4.   

    小妹小问的是在父类的构造器中调用this.show();怎么执行的是子类的show方法呢?小妹新手,请大神解释一下!
      

  5.   

    自己debug一下,看看程序运行的顺序,立马清晰了很多