gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:45:53 25 4
gpt4 key购买 nike

考虑下面的类:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com