Reputation: 1873
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);
}
Upvotes: 11
Views: 10700
Reputation: 5064
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);
}
...
}
Upvotes: 2
Reputation: 1605
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).
Upvotes: 0
Reputation: 285405
pros of not extending JFrame (or any Swing component for that matter):
int getX()
and int getY()
methods. Try it and you'll see some not so funny abnormal behaviors.Upvotes: 10
Reputation: 137272
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
.
Upvotes: 11