【问题标题】:Calling multiple superclass constructors调用多个超类构造函数
【发布时间】:2015-01-05 04:43:45
【问题描述】:

请阅读以下代码。我一直保持非常简单易懂。它不包含任何错误...

class A {
    private int a;
    private int b;

    A() {
        System.out.println("a and b: " + a + " " + b);
    }

    A(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

class B extends A{
    B(int a, int b) {
        super(a,b);
        super(); // error, "Constructor call must be the first statement in a constructor"
    }
}


public class Construct {

    public static void main(String[] args) {
        A a = new B(3,4);
    }
}

我需要知道在这种情况下如何调用超类 A 的无参数构造函数?这样我就可以显示a和b的值。请详细说明。

【问题讨论】:

    标签: java constructor superclass super


    【解决方案1】:

    你不能从子类构造函数中调用两个超类构造函数。您的替代方法是从超类的另一个构造函数调用超类 A 的无参数构造函数。

    A(int a, int b) {
        this ();
        this.a = a;
        this.b = b;
    }
    
    class B extends A{
        B(int a, int b) {
            super(a,b);
        }
    }
    

    【讨论】:

    • 感谢您这么快的回复...但是您能写代码解释一下吗?请提出要求。我今天学到了很多困难的东西。
    • @PirateX 注意在调用this()时a和b不会被初始化。
    • 我知道如何使用 this(),但是你知道 this() 必须是第一个语句。之后我正在初始化值。
    • 您好 user2336315 感谢您的回复,您能告诉我其他选择吗?
    • @PirateX 如果你想从 B 类构造函数中的任意位置调用 A 类的一些初始化逻辑,你可以将该逻辑移动到 A 类的常规方法中,它没有限制构造函数调用有。
    【解决方案2】:

    您应该重新考虑面向对象的设计。具有较少参数的构造函数调用具有更多参数的构造函数,而不是相反。所以你会这样做:

    class A {
        private int a;
        private int b;
    
        A() {
            this(0, 0);  // default constructor: initialize with some useful default values
        }
    
        A(int a, int b) {
            this.a = a;
            this.b = b;
            System.out.println("a and b: " + this.a + " " + this.b);
        }
    }
    
    class B extends A{
        B(int a, int b) {
            super(a,b);
        }
    }
    
    
    public class Construct {
    
        public static void main(String[] args) {
            A a = new B(3,4);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-19
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多