【问题标题】:Java super() inheritanceJava super() 继承
【发布时间】:2012-06-19 13:31:45
【问题描述】:

问题的简短摘要:我有一个由子类扩展的父类。

     public class Parent{

        public Parent(){
          //constructor logic
        }
     }

这个子类使用super调用Parent的构造函数:

     public class Child extends Parent{

         public Child(){
            super();
         }
     }

如果我可以在 Grandchild 类的构造函数中调用 super() 方法,我想知道是否要扩展 Child 类:

    public class Grandchild extends Child{

         public Grandchild(){
            super();
         }
    }

【问题讨论】:

    标签: java oop inheritance


    【解决方案1】:

    这将调用Child 类构造函数,而后者又将调用Parent 类构造函数。

    【讨论】:

      【解决方案2】:

      super() 在继承的上一层调用构造函数,如果有无参数构造函数,它会被隐式调用。

      对象从继承的顶层初始化,在你的例子中它是 Object > Parent > Child > Grandchild。

      来自documentation

      If a constructor does not explicitly invoke a superclass constructor, the Java compiler
      automatically inserts a call to the no-argument constructor of the superclass. If the super 
      class does not have a no-argument constructor, you will get a compile-time error. Object does 
      have such a constructor, so if Object is the only superclass, there is no problem. 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-11
        • 2018-05-30
        • 2017-08-10
        • 1970-01-01
        • 1970-01-01
        • 2016-07-28
        • 1970-01-01
        • 2016-02-25
        相关资源
        最近更新 更多