在构造函数中调用另一个构造函数AND parent的构造函数

时间:2013-01-09 20:51:44

标签: java oop inheritance

考虑以下课程:

class MyPanel extends JPanel {

   public MyPanel() {
      super();

      // Do stuff
   }

   public MyPanel(LayoutManager manager) {
      super(manager);

      // Do same stuff as the first constructor, this() can't be used
   }

}

在尝试避免重复代码时,第二个构造函数出现了问题。这是因为我无法在同一个构造函数中同时调用super()this()

我可以将公共代码提取到一个单独的方法中,但我确信必须有一个更优雅的解决方案来解决这个问题?

2 个答案:

答案 0 :(得分:5)

经常使用的一种模式是

class MyPanel extends Panel {
  MyPanel() {
    this(null);
  }

  MyPanel(LayoutManager manager)
    super(manager);
    // common code
  }
}

但只有在Panel()Panel(null)相同时才有效。

否则,常用方法似乎是最好的方法。

答案 1 :(得分:5)

虽然你不能调用多个构造函数,但你可以做的是这样的:

class MyPanel extends JPanel {

  public MyPanel() {
     this(null);
  }

  public MyPanel(LayoutManager manager) {
     super(manager);
     // Do all the stuff
  }

}

但是你最终会得到一些更混乱的东西。正如您所说,初始化方法可以是另一种方法:

class MyPanel extends JPanel {

  public MyPanel() {
     super();
     this.initialize();
  }

  public MyPanel(LayoutManager manager) {
     super(manager);
     this.initialize();
     // Do the rest of the stuff
  }

  protected void initialize() {
     // Do common initialization
  }

}