从孙子类调用父类构造函数会调用父类还是祖父类的构造函数?

3

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

//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)?
}

假设所有三个类的类型(按命名约定为Class Type)相同,而varFirst也是Type的实例,则是的。可以尝试以下示例:将类型替换为int,并在每个构造函数中使用System.out.println(intValue);->构造函数Third将向Second传递一个值,例如2,并将其传递给First,但sysout的打印顺序将是First-Second-Third(简而言之,Third仅调用Second,但Second将调用First,流程继续进行)。 - Srinath Ganesh
2个回答

7

super调用直接父类的构造函数。 因此,在Third中的super调用将调用Second的构造函数,这将依次调用First的构造函数。如果在构造函数中添加一些打印语句,您很容易就能看到这一点:

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

0

在子类中,super 尝试从父类获取信息,而在父类中,super 尝试从祖先类获取信息。

    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
            */
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接