问题
What are the pros and cons of extending a JFrame rather than create a new JFrame?
For example:
public class Test extends JFrame {
setVisible(true);
}
or
public class Test {
JFrame test = new JFrame():
test.setVisible(true);
}
回答1:
You should not extend a class, unless you want to actually extend its functionality, in the example you've shown, you should use option 2, as option 1 is an abuse of the extend
ing feature.
In other words - as long as the answer to the question is Test a JFrame
? is NO, it should not extend JFrame
.
回答2:
pros of not extending JFrame (or any Swing component for that matter):
- Avoid unintentional method overrides. I've stepped into this several times, first when I gave my class
int getX()
andint getY()
methods. Try it and you'll see some not so funny abnormal behaviors. - Simplify the method options available when using Eclipse or NetBeans to only those methods you've created. This is actually my favorite advantage.
- Gearing your GUI's to create JPanels rather than JFrames which increases deployment flexibility 100-fold.
- And most importantly, exposing only that which needs exposing.
回答3:
If extending JFrame, I would want to modify/customize my current Jframe class and so subclass can use this customized implementation.
If there nothing that I want to do change in the JFrame class, just use the existing like in second snippet that you've given in your code. By use, I mean by creating other JComponent (button/label for examples), etc, in a JPanel and create an object Test and set the JFrame contentPane to this object. Something like
public class Test extends JPanel {
public class() {
// add buttons/label here
}
...
private static void createAndShowGUI() {
JFrame frame = new JFrame();
Test object = new Test();
frame.setContentPane(object.setOpaque(true));
frame.setVisible(true);
}
...
}
回答4:
One of the rules of OOD: If you can not inherit (extend) the classes you do not inherit their.
Inheritance increases the complexity and connectedness of the program and potentially lead to new errors. In your case there are not any reasons to extend class.
You should extends classes only when you need to get access to protected members and/or or get polymorphic behavior (override virtual methods).
来源:https://stackoverflow.com/questions/10442665/extending-a-jframe