从孙类调用超类构造函数,调用父级或祖父级构造函数



当使用二级子类的超类构造函数时,它是将参数传递给祖父构造函数还是直接父构造函数?

//top class
public First(type first){
  varFirst = first;
}
//child of First
public Second(type second){
  super(second); //calls First(second)
}
//child of Second
public Third(type third){
  super(third); //calls First(third) or Second(third)?
}

super调用直接父级的构造函数。因此,Third中的super调用将调用Second的构造函数,而构造函数又调用First的构造函数。如果您在构造函数中添加一些 print 语句,这很容易自己看到:

public class First {
    public First(String first) {
        System.out.println("in first");
    }
}
public class Second extends First {
    public Second(String second) {
        super(second);
        System.out.println("in second");
    }
}
public class Third extends Second {
    public Third(String third) {
        super(third);
        System.out.println("in third");
    }
    public static void main(String[] args) {
        new Third("yay!");
    }
}

您将获得的输出:

in first
in second
in third

sub 中的 super 尝试从 Parent 获取信息,而 Parent 中的 super 尝试从 GrandParent 获取信息。

    public class Grandpapa {
    public void display() {
        System.out.println(" Grandpapa");
    }
    static class Parent extends Grandpapa{
        public void display() {
            super.display();
            System.out.println("parent");
        }
    }
    static class Child extends Parent{
        public void display() {
        //  super.super.display();// this will create error in Java
            super.display();
            System.out.println("child");
        }
    }
    public static void main(String[] args) {
            Child cc = new Child();
            cc.display();
 /*
            * the output :
                 Grandpapa
                 parent
                 child
            */
    }
}