为什么不扩展JFrame和其他组件? [英] Why shouldn't you extend JFrame and other components?

查看:126
本文介绍了为什么不扩展JFrame和其他组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到过这里出现过几次,但在我看过的帖子中,没有人解释过。为什么我不应该扩展JFrame(或任何组件)?是否存在我应该扩展组件的条件,或者这是一个你不遵守的确定规则?

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?

推荐答案

一般来说,扩展组件往往严格地使用组件。这在设计方面以不必要的方式严重限制了您的选项,因此您的类无法扩展不同的类,您无法隐藏JFrame的方法,导致它更难以维护,并且在使用类时更容易触发意外错误。

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.

话虽这么说,当您希望子类将特定于项目的功能添加到Frame(例如方便方法等)时,子类应该没用,其中子类将被用于代替Frame本身,但用作框架通常,不是应用程序中特定框架的视图。

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.

这篇关于为什么不扩展JFrame和其他组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆