从孙子类调用超类构造函数,调用父或祖父项构造函数?

时间:2016-03-19 07:57:12

标签: java inheritance constructor super constructor-overloading

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

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

2 个答案:

答案 0 :(得分:6)

super调用直接父级的构造函数。因此,super中的Third电话会调用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

答案 1 :(得分:0)

super in Child尝试从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
            */
    }
}