Zar*_*Zar 0 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
}
}
Run Code Online (Sandbox Code Playgroud)
当试图避免重复代码时,第二个构造函数中出现问题.这一点,因为我不能把两者super()并this()在同一构造.
我可以将公共代码提取到一个单独的方法中,但我确信必须有一个更优雅的解决方案来解决这个问题?
经常使用的一种模式是
class MyPanel extends Panel {
MyPanel() {
this(null);
}
MyPanel(LayoutManager manager)
super(manager);
// common code
}
}
Run Code Online (Sandbox Code Playgroud)
但是,只有当工作Panel()和Panel(null)是等价的.
否则,常用方法似乎是最好的方法.
虽然你不能调用多个构造函数,但你可以做的是这样的:
class MyPanel extends JPanel {
public MyPanel() {
this(null);
}
public MyPanel(LayoutManager manager) {
super(manager);
// Do all the stuff
}
}
Run Code Online (Sandbox Code Playgroud)
但是你最终会得到一些更混乱的东西.正如您所说,初始化方法可以是另一种方法:
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
}
}
Run Code Online (Sandbox Code Playgroud)