【问题标题】:what happens if the argument structure for a subclass constructor call does not match it's superclass constructor如果子类构造函数调用的参数结构与它的超类构造函数不匹配会发生什么
【发布时间】:2014-06-05 10:46:39
【问题描述】:
    1234563子类如何调用它的超类构造函数?
  1. 这种情况下是否使用super()的默认构造函数?

  1. 仅当没有调用this()super() 作为子类的第一行时才使用默认构造函数?

【问题讨论】:

    标签: java inheritance constructor super


    【解决方案1】:
    1. 你必须直接调用你喜欢的super contructor,除了超级有一个没有参数的“可见”构造函数。
    2. 仅当它是可访问的(公共的或受保护的)并且没有与其签名匹配的其他构造函数时。

    样本:


    父构造函数:

    public Parent();
    public Parent(int x, int y);
    

    子构造函数:

    public Child() {
       // invokes by default super() if there is no other super call.
    }
    
    public Child(int x, int y) {
       // invokes by default super() if there is no other super call.
    }
    

    但是如果你将父构造函数定义为私有

    父构造函数:

    private Parent();
    public Parent(int x, int y);
    

    子构造函数:

    public Child() {
       // does not compile due there is no "visible" super().
    }
    
    public Child(int x, int y) {
       // does not compile due there is no "visible" super().
    }
    

    你需要直接调用超级构造函数

    public Child() {
       super(1,2);
    }
    
    public Child(int x, int y) {
       super(x,y);
    }
    

    【讨论】:

      【解决方案2】:

      从 SubClass 构造函数中调用 SuperClass 构造函数的方式如下。

      1 SuperClass 没有默认构造函数,这意味着 SuperClass 有一个带参数的构造函数。例如

      SuperClass(int a){
           //somethin
      }
      

      您必须从子类构造函数中显式调用超类构造函数,否则您的程序将无法编译。前任。

      Subclass(){
            super(10);
      }
      

      2 > SuperClass 有一个默认构造函数,它可以不定义任何构造函数,也可以定义一个默认构造函数。在这种情况下,您不需要从子类 1 调用超级构造函数,但如果您愿意,可以通过调用来调用。

       Subclass(){
           super();
        }
      

      请记住,您只能从任何构造函数调用另一个构造函数。 例如。

      SubClass(){
         super();
         this(10);//this will not compile either you can call this or super
      }
      

      【讨论】:

        猜你喜欢
        • 2021-07-24
        • 1970-01-01
        • 2011-05-20
        • 2012-05-10
        • 2021-09-19
        • 2018-02-28
        • 2016-11-20
        • 2016-07-19
        相关资源
        最近更新 更多