调用多个超类构造函数

问题描述:

请阅读以下代码。我保持它很容易理解。它不包含任何错误...调用多个超类构造函数

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的值。请详细解释。

您不能从子类构造函数中调用两个超类构造函数。另一种方法是从超类的另一个构造函数中调用超类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); 
    } 
} 
+0

感谢您的回复如此之快......但您能否通过编写代码来解释它?请其提出请求。今天我学到了很多困难的事情。 – PirateX 2014-11-08 13:00:55

+0

@PirateX查看我的编辑 – Eran 2014-11-08 13:01:50

+1

@PirateX请注意,在调用'this()'时,a和b不会被初始化。 – user2336315 2014-11-08 13:02:37

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

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); 
    } 
}