考虑下面的类:
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/