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

2 回答 2

7

super调用直接父级的构造函数。所以super调用Third会调用Second's 的构造函数,而后者又会调用First's. 如果您在构造函数中添加一些打印语句,您自己很容易看到这一点:

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
于 2016-03-19T08:07:47.750 回答
0

Child 中的 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
            */
    }
}
于 2018-03-11T15:34:26.833 回答