【问题标题】:Calling super class constructor from grandchild class, calls parent or grandparent constructor?从孙子类调用超类构造函数,调用父或祖父构造函数?
【发布时间】:2016-03-19 07:57:11
【问题描述】:

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

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

【问题讨论】:

  • 假设所有 3 个 Classes 的类型(根据命名约定的类类型)都相同,并且 varFirst 也是 Type 的一个实例,那么 Yes ,您可以尝试示例: 用 int 和每个构造函数 System.out.println(intValue); 替换类型-> 构造函数 Third 将传递一个值,例如 2 到 Second 和 First 但是 sysout 的打印将按照 First-Second-Third 的顺序(简而言之,Third 只会调用 Second,但 Second 会调用 First 和流程继续)

标签: java inheritance constructor super constructor-overloading


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      相关资源
      最近更新 更多