java - 在构造函数内调用另一个构造函数和父级的构造函数

标签 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()

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

最佳答案

虽然您不能调用多个构造函数,但您可以执行以下操作:

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
  }

}

关于java - 在构造函数内调用另一个构造函数和父级的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14246246/

相关文章:

java - 来自 Spring MVC Controller 的异步调用

java - 我无法从扩展 List 接口(interface)的类中调用方法

php - 上传文件不支持ajax

Java - 子类构造函数中的显式 super()

C# 继承 : change field data type and value in derived class

java - 将JUL相关的log4j 1.2配置转换为log4j 2配置

java - war 文件没有爆炸的原因可能是什么?

java - 使用子类和父类(super class)的不死族和吸血鬼程序

java - ruby 和鸭子打字: design by contract impossible?

javascript - 面向对象的Javascript