class A{
A(){
this("1","2");
}

A(String s){
System.out.print(s);
}

A(String s1,String s2){
this(s1+s2);
}
}class B extends A{
B(){
super("4");
}
B(String s){
System.out.println(s);
 
}
B(String s1,String s2){
this(s1+s2+"3");
}
}public class test {
 
public static void main(String[] args) {
 B b = new B("test"); }}

解决方案 »

  1.   

    怎么好理解了?结果应该是test,12是从哪里来的?
      

  2.   

    要创建子类,总得先创建“属于”父类的那部分,可以在子类的构造方法中显示地用
    super()来构造父类(必需是第一条语句),若是不写的话,默认就调用父类的无参构造方法。
      

  3.   

    通常写this的时候,都是指“这个对象”或者“当前对象”。
    在构造器中,如果为this添加了参数列表,将产生对符合此参数列表的某个构造器的明确调用。
    体会一下A类的三个构造器。
      

  4.   

    生成一个对象时,也就是new 子类构造方法()
    在子类构造方法的【第一行】会有三种情况
    (1)this(有入参or无入参),作用:调用同类其他的构造方法
    (2)super(有入参无入参),作用:调用父类的构造方法
    (3)不写this(有入参or无入参)和super(有入参无入参),就会默认super(),作用:调用父类无参构造B(String s){
    System.out.println(s);
      
    }
    第一行不是执行System.out.println(s);而是上面的第三种情况,缺省的super();所以执行
    A(){ 
    this("1","2"); 
    }
      

  5.   

    B b = new B("test");
    会调用
    B(String s){
        super(); //--1 这里隐式调用A的无参构造方法,LZ可以试着把A的无参构造方法去掉,会发现无法编译
        System.out.println(s);
    }--1会调用
    A(){ 
        this("1","2"); // --2
    }--2会调用
    A(String s1,String s2){
        this(s1+s2); // --3
    }--3会调用
    A(String s){
        System.out.print(s); 
    }所以--3打印 12
    然后回到--2,然后回到--1,然后打印B(String s)构造方法的"test"
    所以结果就是12test
      

  6.   

    class A{
    A(){ 
    this("1","2"); 
    }A(String s){
    System.out.print(s); 
    }A(String s1,String s2){
    this(s1+s2); 
    }
    }class B extends A{
    B(){
    super("4"); 
    }
    B(String s){
    System.out.println(s);
      
    }
    B(String s1,String s2){
    this(s1+s2+"3"); 
    }
    }public class test {
     
    public static void main(String[] args) {
    B b = new B("test");//子类B调用子类B的有参构造方法,B(String s){System.out.println(s);}
    //打印test,而楼主忽略了一定,由于子类是从父类继承的,若想构造子类,所以得先构造父类,而规定当子类的构造方法中没有显示的调用父类的构造方法时,默认调用父类的无参构造方法,所以先执行A(){ 
    this("1","2");},而this代表当前对象的引用,是A类对象,相当于调用了A(String s1,String s2){
    this(s1+s2); }方法,而s1+s2是由俩个字符串并连接起来,即“12”,变成了this(“12”),接着就调用了A(String s){System.out.print(s); }方法,打印出s,即结果中多余的12,后面的不用说了吧
    }
    }}