我需要知道在java中是否可以进行这种构造函数链调用?我正在扩展基础JButton类,我首先需要初始化超级变量,然后使用默认构造函数初始化我的类.
public CustomButton(){
try {
URL inp = CustomButton.class.getResource("/icons/noa_en/buttonBackground.png");
background = ImageIO.read(inp);
} catch (IOException e) {
e.printStackTrace();
}
}
public CustomButton(ImageIcon img){
super(img);
this();
}
Run Code Online (Sandbox Code Playgroud)
要么 :
public CustomButton(ImageIcon img){
this();
super(img);
}
Run Code Online (Sandbox Code Playgroud)
你只能在构造函数中调用另一个构造函数作为你的第一个动作.因此,当您想要在类的两个构造函数中调用不同的超类构造函数时,您必须将公共代码重构为单独的方法:
public CustomButton() {
// implicitly calls super() here
setup();
}
public CustomButton(ImageIcon img) {
super(img);
setup();
}
private void setup() {
// your init code
}
Run Code Online (Sandbox Code Playgroud)