Why shouldn't you extend JFrame and other components? [duplicate]

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?


Solution 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.

Solution 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.

Solution 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.

Solution 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.