-->

Why shouldn't you extend JFrame and other comp

2019-01-02 20:56发布

问题:

I've seen this come up here a few times, but in the postings I've seen, no one explained it. Why shouldn't I extend JFrame (or any component)? Are there conditions where I should extend a component, or is this a firm rule that you don't?

回答1:

Generally speaking, extending the component tends to be done strictly to use the component. This severely limits your options in unnecessary ways in terms of design, so that your classes can't extend different classes, you can't hide the JFrame's methods causing it to be more difficult to maintain and easier to trigger unexpected bugs when using the class.

Typically the intention is strictly to use the class to draw a frame, and composition is preferred over inheritance.

That being said, subclassing should be fine when you intend your subclass to add project-specific functionality to the Frame (such as convenience methods and the like) where the subclass would be used instead of the Frame itself, but used as a frame in general, not as a view of a specific frame in the application.



回答2:

Prefer composition over inheritance. All the usual reasons. Composition forces less dependencies between code.

Swing, and event AWT, components are hideously complicated. You don't want to be getting into that mess. You can easily override methods accidentally. In cases where you do need to override methods, it's difficult to see where that is done if it is amongst normal code.



回答3:

If your application REALLY is just a JFrame, go ahead and extend it. However, it's best to use object composition rather than inheritance if you are simply using a JFrame.

If your object extends some other object you would have no choice in the matter, as an example.



回答4:

I don't see the problem as long as you are extending the class and can preserve the "is-a" aspects of inheritance.

When you extend a JPanel but your new object is not a true specialization of JPanel, that is where you get into trouble. But if you create a new SpeciallyFormattedJLabel that extends JLabel, I see no problem with that.



回答5:

I know this is an old post, but I just came across it and I gotta tell you... extending limited my options of calling certain actions of the object. I'm actually rewriting some parts of the code now to get rid of the damage that extended has caused me. Unless I'm writing a one-file program, I'm not going to use extended again.



标签: